Swift Tip - Closure retain cycle

Avoid calling self inside your closure as much as possible.

1
2
3
let tower = { [weak self] rapunzel in
return self?.knight.save(rapunzel)
}

What if self is nil? I know what you’re thinking. Forget unowned! Just pass a capture list with the properties you need inside the closure.

1
2
3
let tower = { [knight] rapunzel in
return knight.save(rapunzel)
}

And that is how it is done.

Partager Commentaires