DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 7/100)

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) 
Enter fullscreen mode Exit fullscreen mode

With return value:

func rollDice() -> Int { return Int.random(in: 1...6) } for i in 1...6 { print("\(i): \(rollDice())") } 
Enter fullscreen mode Exit fullscreen mode

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]) 
Enter fullscreen mode Exit fullscreen mode

Return an arrary:

func abc() -> [Int] {} 
Enter fullscreen mode Exit fullscreen mode

Return a dictionary:

func abc() -> [String: Int] {} 
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

Or:

func getUser() -> (String, String) { return ("Taylor", "Swift") } let user = getUser() print(user.0) print(user.1) 
Enter fullscreen mode Exit fullscreen mode

Use _ to omit the parameter name:

func isUppercase(_ string: String) -> Bool { string == string.uppercased() } let string = "HELLO, WORLD" let result = isUppercase(string) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)