Reusing Closures in Swift

Which of the following is better:

Sample1:

var x: Int = 0
for _ in 1...5 {
    someList.append( Foobar(someClosure: { println("X = \(x)") }))
}

Sample2:

var x: Int = 0
var c: ()->() = { println("X = \(x)") }
for _ in 1...5 {
    someList.append( Foobar(someClosure: c))
}
  • If I think of closure as reference types, then sample2 would be better since I am reusing the same object (reduce memory allocation, reuse objects).
  • If I think of closure as value types, then it really doesn't matter. I would have to trust the compiler to find out that the closure is the same and that he knows that it uses the same closure (similar to what happens if I use the same literal string in my code in several places). Choosing one over the other will be considered "premature optimization."

Edit:

Is there a fundamental difference between the two samples (in addition to the writing style)?

+4
1

"". - Swift. , "".

. , , - :

var c: ()->() = { println("X = \(x)") }

:

func c() {
    println("X = \(x)")
}

. - .

, . , , , . :

for _ in 1...5 {
    someList.append( Foobar(someClosure: { println("X = \(x)") }))
}

, , , , . , .

: ( , , [weak self] in), . ​​, .

+5

All Articles