🔰function as variable

assign function to a variable

Swiftbasic typesfunction ⟩ as variable

// 1. define function "add"
func add(a: Int, b: Int) -> Int {
    let result = a + b
    print(result)
    print(#function)         // "add(a:b:)" (function signature)
    return result
}

// 2. call add() function (with "argument labels")
let n1 = add(a: 2, b: 3)     // 5, "add(a:b:)"

// --------------------------------------------------------------
//
//     let n3 = add(2, 3)    // ⛔ error: missing argument labels 'a:b:' in call
//
// --------------------------------------------------------------

// ⭐️ 3. assign to a variable 
//
let add2 =   add
//        ╰──F.E.──╯  (⭐️ F.E.: function expression)
//
// ⭐️ `add2` is now a "closure". 
//   • share the same function body with `add`.
//   • but can't use "argument labels" when calling it.

// ⭐️ 4. call "add2" function (without "argument labels")
let n2 = add2(5, 6)                 // 11, "add(a:b:)"

// --------------------------------------------------------------
//
//     let n4 = add2(a: 5, b: 6)    // ⛔ error: extraneous argument labels 'a:b:' in call
//                                  //    (extraneous: 無關的)
// --------------------------------------------------------------

// function type
print(type(of: add))    // (Int, Int) -> Int
print(type(of: add2))   // (Int, Int) -> Int

Last updated

Was this helpful?