Last updated 1 min read

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