Search code examples
swiftcomputed-properties

What is the difference between the following 3 declarations?


var title: UILabel {
    let label = UILabel()
    textLabel.font = .systemFontOfSize(13)
    return label
}

let title: UILabel = {
    let label = UILabel()
    textLabel.font = .systemFontOfSize(13)
    return label
}()

lazy var title: UILabel = {
    let label = UILabel()
    textLabel.font = .systemFontOfSize(13)
    return label
}()

If I put 'let' in the first one, compiler will complain that 'computed property do not allow let'. Ok, kind of makes sense. The only difference between the first one and second is '=' and '()'. So, does it mean that it is not a computed property anymore?


Solution

  • 1.

    var title: UILabel {
        let label = UILabel()
        textLabel.font = .systemFontOfSize(13)
        return label
    }
    

    It is a read only computed property. Computed properties cannot be let. These are calculated using other stored/computed properties. So they don't have any backing store of their own. Hence, computed properties are always declared as var.

    2.

    let title: UILabel = {
        let label = UILabel()
        textLabel.font = .systemFontOfSize(13)
        return label
    }()
    

    It is a stored property. This is assigned a closure that returns a UILabel object. This closure is executed during the instantiation process of the object and the returned UILabel object is assigned to title.

    3.

    lazy var title: UILabel = {
        let label = UILabel()
        textLabel.font = .systemFontOfSize(13)
        return label
    }()
    

    It is a lazy stored property. It is also assigned a closure that returns a UILabel object. But this closure is not executed during the instantiation process. It is executed whenever this property is first used. After the execution of the closure, the UILabel object returned is assigned to title.