Swift
- functions
- function parameter names
- return one value & return multiple values
- call function without explicit parameter name
Define functions
We need to write the parameter name as part of the function call. This isn’t common in other languages, but I think it’s really helpful in Swift as a reminder of what each parameter does.
func printTimesTables(number: Int, end: Int = 10) { for i in 1...end { print("\(i) x \(number) is \(i * number)") } } printTimesTables(number: 2)
With return value:
func rollDice() -> Int { return Int.random(in: 1...6) } for i in 1...6 { print("\(i): \(rollDice())") }
Take a list of int as parameter:
func square(numbers: [Int]) { for number in numbers { let squared = number * number print("\(number) squared is \(squared).") } } square(numbers: [2, 3, 4])
Return an arrary:
func abc() -> [Int] {}
Return a dictionary:
func abc() -> [String: Int] {}
Return a tuple that contains multiple values:
func getUser() -> (firstName: String, lastName: String) { return (firstName: "John", lastName: "Doe") } let user = getUser() print(user.firstName) print(user.lastName) // or let (firstName, lastName) = getUser() print(firstName) print(lastName)
Or:
func getUser() -> (String, String) { return ("Taylor", "Swift") } let user = getUser() print(user.0) print(user.1)
Use _
to omit the parameter name:
func isUppercase(_ string: String) -> Bool { string == string.uppercased() } let string = "HELLO, WORLD" let result = isUppercase(string)
Top comments (0)