Andrew
Andrew

Reputation: 238717

What is this `[unowned self] in` Swift code doing?

I came across this Swift code that I don't understand. What is the navigationCallback being assigned to? What is [unowned self]? I think I would understand this better if I could see the equivalent example in Objective-C.

navigationCallback = { [unowned self] in
    previousNavigationCallback?()
    if self.state != .Canceled {
        callback()
    }
}

Upvotes: 0

Views: 5346

Answers (2)

matt
matt

Reputation: 535139

What is the navigationCallback being assigned to?

The stuff in curly braces constitutes an anonymous function. It's like a block in Objective-C.

What is [unowned self]?

The stuff in square brackets preceding in in the anonymous function's capture list. It prevents a retain cycle by bringing self into the anonymous function unretained. unowned is like an assign property policy in Objective-C (non-ARC weak). In Objective-C you'd typically do the weak-strong dance in order to do something similar.

Upvotes: 6

Duncan C
Duncan C

Reputation: 131418

That construct is called a "Capture list". As Matt says, it lets the closure/block/anonymous function have an unowned reference to self inside the block. It lets you avoid retain cycles caused by closures that have a strong reference to the object that creates them, when the creating object also has a strong reference to the closure.

This is covered in detail in Apple's Swift iBook. Here's a brief excerpt:

Resolving Strong Reference Cycles for Closures You resolve a strong

reference cycle between a closure and a class instance by defining a capture list as part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference. The appropriate choice of weak or unowned depends on the relationships between the different parts of your code.

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2).” iBooks. https://itun.es/us/jEUH0.l

Upvotes: 3

Related Questions