Search code examples
swiftblockretain-cycle

Why specify [unowned self] in blocks where you depend on self being there?


I want self to be non-nil and I'm sure it will be, during the blocks execution. So why explicitly specify [unowned self] ?

object.executeBlock {
    date = self.lastModified
}

vs

object.executeBlock { [unowned self] in
    date = self.lastModified
}

Edit: Well i'm getting down votes so let's try again. Q: Let’s say I have a problem. That problem is that I would like to prevent a reference cycle. I have two options. I could use [unowned self] or I could use [weak self]. My question therefore, is this: from these two options, why would I choose [unowned self] ? Why not choose [weak self] everytime ?


Solution

  • "The Language Guide claims you should use unowned if the closure and containing object reference each other and will be destroyed at the same time. Presumably that's to avoid the cost of safely nil'ing out a weak reference in an object that's about to dealloc anyway."

    http://www.russbishop.net/swift-capture-lists

    So [unowned self] makes self an an implicitly unwrapped optional, for the convenience of not unwrapping it yourself, at the risk of a crash if of course it is actually nil.