The difference between function assignment and closure

Is there a difference between a quick function declaration:

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

and circuit purpose:

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

Is there a difference between the two?

+6
source share
2 answers
  • Named or Anonymous

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

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

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

    Similarly, but not the same using closure:

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

     func function<T>(x:T) { ... } 
  • Ordering from your own original declaration
    only supported in global :

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

    You can also do this with a closure:

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

    But this is not recommended because it causes strong reference loops.

  • overload
    only supported in features:

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

    nb You can refer to them as closing as follows:

     let f:(Float) -> Void = function 
+5
source

Another difference: recursion 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() } } 
0
source

Source: https://habr.com/ru/post/978180/


All Articles