user1040049
user1040049

Reputation:

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))
}

Edit:

Is there a fundamental difference between both samples (aside from writing style)?

Upvotes: 4

Views: 1037

Answers (1)

matt
matt

Reputation: 535249

You're misusing the word "closure". All functions are closures in Swift. So you just mean "function".

A function can have a name. The way you show is one way to give a function a name:

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

But here's another way:

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

That's right. Declaring a function is just a way of giving a function a name.

However, a function can also be anonymous, meaning it has no name. That's just a way of making the code shorter when no name is needed, because the function body can be defined inline in the one place where it is used. You show an example of that too:

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

So give a function a name if you want to or need to, and don't if you don't. There's no advantage, disadvantage, or difference one way or the other.

Except for one thing: an anonymous function can have a capture list (defining the memory management of class instances captured from outside the function body, e.g. [weak self] in), but a declared function cannot. I regard that as a bug in the language, though not a very serious one.

Upvotes: 6

Related Questions