iOS Closures in Swift First Class Functions Functions as Data

Shaan Marok
PRO
Shaan Marok
Pro Student 1,015 Points

Assigning functions to variables in Swift

When we assign functions to variables in Swift, are the labels always omitted or is there a way to include them?

Example, for argument labels a and b

func sum(a: Int, b: Int) -> Int {
    return a + b
}

let addTwoNumbers: (Int, Int) -> Int = sum
addTwoNumbers(1, 2)
Jeff McDivitt
Jeff McDivitt
23,960 Points

They are included you omit them with an underscore before the the variable

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

let myAdd = add(12, 13)

1 Answer

Vansh Agarwal
PRO
Vansh Agarwal
Pro Student 3,964 Points

Yes, they are always omitted when you assign that function to a constant or variable. So if you call the function using the constant or variable name, there will be no argument labels as its type( the function signature ) does not include any argument labels. However if you call the function using the function name directly, there will be argument labels( if you have made labels ).