Lazy Vars in Swift Do Not Capture
#Swift, #Software Engineering
Lazy init property is Swift is a non-escaping closure. It doesn't capture anything so it doesn't capture self.
This is fine:
class Test {
    lazy var tableView: UITableView = {
        let tableView = UITableView(...)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
}
However, it should never be confused with a property containing a closure. Because it DOES capture.
To avoid it retain cycle and a memory leak weak or unowned references should be used.
class Test {
    lazy var tableView: () -> UITableView = { [unowned self] in
        let tableView = UITableView(...)
        tableView.delegate = self
        tableView.dataSource = self    
        return tableView
    }
}
References
- Does lazy var capture self?
- Properties | Documentation
- swift - Lazy initialisation and retain cycle - Stack Overflow
- ios - What is difference between @noescape, @escaping and @autoclosure? - Stack Overflow
- closures - Must all variable or lazy variable initializer in Swift include weak self? - Stack Overflow
Comments