Day 5 of 100 days of SwiftUI
Oluwasanmi Aderibigbe
Posted on March 19, 2021
Day 5 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about functions.
Functions in computer programming let us reuse code without repeating ourselves. In Swift, functions are written like this
func addNumbers(first: Int, second: Int) -> Int {
return first + second
}
let sum = addNumbers(first: 1, second: 2)
print(sum)
The code above contains a function that collects two numbers are parameters and returns their sum. To return more than one value from a function, you could simply return a tuple instead.
Functions in swift have many cool features like default, inout, and variadic parameter values.
Making a default parameter value in Swift is as simple as assigning a value to the parameter. For example
func getPhotos(from: String, quantity: Int = 30) -> [Photos] {
// get photos from the internet and return an array of photos of size quanity
}
getPhotos("instagram.com")
getPhotos("instagram.com", 50)
The code above creates a function that gets an array of photos from the internet. By default, the number of photos to be gotten from the server is 30. By assigning quantity: Int = 30
. if no argument is passed into the function, 30 would be used instead. That means getPhotos("instagram.com")
gets 30 photos while getPhotos("instagram.com", 50)
gets 50 photos
The inout
keyword is used when you want to change the value of a parameter inside a function. By default in swift and, most programming parameters are constant.
func squareNumber(number: inout Int) {
number *= number
}
var value = 3
squareNumber(number: &value)
print(value)
For example, the code above creates a function that takes a number and squares it inside of the function. When calling the function you have to add &
keyword. This means you are passing it into an inout parameter. Most of the time, it's best just to return a value from the function rather than using the inout parameter.
With variadic functions, you can pass in any number of parameters. Variadic means the number of parameters varies. In swift a variadic parameter is written with an ellipsis.
func addNumbers(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
let sum = addNumbers(numbers: 1,2,3,4,5,6)
print(sum)
If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Posted on March 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.