Krzysztof Kaczor
Krzysztof Kaczor

Reputation: 5588

Difference between function and closure assignment

Is there any difference in swift between function declaration:

func function(a: String) {
    print(a);
}
function("test");

and closure assignment:

let closure = {
    (a: String) in
    print(a);
}
closure("test");

Is there any difference between those?

Upvotes: 6

Views: 344

Answers (2)

rintaro
rintaro

Reputation: 51911

  1. Named or anonymous

    func function(a: String) {
        print("\(a), name: \(__FUNCTION__)");
    }
    
    let closure = { (a: String) in
        print("\(a), name: \(__FUNCTION__)");
    }
    
  2. Capture List
    supported in closures only:

    let obj = FooClass()
    let closure = { [weak obj] in ... }
    
  3. Curried function
    supported in functions only:

    func curriedFunc(x:Int)(y:Int) { ... }
    let curried = curriedFunc(1)
    curried(y:2)
    

    Similar, but not exact the same with using closure:

    let closure = { (x:Int) in { (y:Int) in ... }}
    
  4. Generics
    supported in functions only:

    func function<T>(x:T) { ... }
    
  5. Referenceability from its own initial declaration
    supported in global functions only:

    func recursive(var x:Int) -> Int {
        ...
        return condition ?  x : recursive(x)
    }
    

    You can do this using closure also:

    var recursive:((Int) -> Int)!
    recursive = { (var x) in
        ...
        return condition ? x : recursive(x)
    }
    

    But this is not recommended because this causes strong reference cycles.

  6. Overload
    supported in functions only:

    func function(a: String) { print("String: \(a)") }
    func function(a: Float) { print("Float: \(a)") }
    

    n.b. You can reference them as a closure like this:

    let f:(Float) -> Void = function
    

Upvotes: 5

newacct
newacct

Reputation: 122439

Another difference: recursivity inside another function

Nested functions cannot be recursive:

func foo() {
    func bar() { bar() } // does not compile
}

but closures inside other functions can be recursive:

func foo() {
    var bar: (() -> ())!
    bar = { bar() }
}

Upvotes: 0

Related Questions