๐Ÿ”ฐfunction as variable

assign function to a variable

Swift โŸฉ basic types โŸฉ function โŸฉ as variable

when you assign a function to a variable, you can't use argument labels on calling this function through that 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