What makes a property a computed property in Swift

后端 未结 4 1078
Happy的楠姐
Happy的楠姐 2020-12-19 10:38

Let\'s started with the code snippet:

St Foo {
    var proA: Int = 0 { // needs initialization
        willSet {
            print(\"about to set proA to \\(         


        
4条回答
  •  情深已故
    2020-12-19 10:47

    A stored property is a property of which the property value is stored together with the instance of the class or struct. The value may be changed, but the property can also be a constant. Thus a stored property can be as simple as:

    var proA: Int
    let proB: Int
    var proC: Int = 0
    

    Computed properties do not store a value. Thus you cannot assign a value to a computed property. A Computed property should have a getter that returns a value. I a broad term, you can think of a computed property as a property that returns the value of a function.

    Example of Computed Property

    var proA: Int {
        return proB * proC
    }
    

    With regards to your questions:

    1. Computed Property is therefor a property that do not store a value, and contains a get to return the 'computed' value of the property.
    2. a is correct, b computed properties should not have initialization, c if you mean willSet and didSet. Yes they are like observers for when the property's value will change and did change respectively
    3. Since the value of a computed property is not stored and will never be used, the compiler forbids it.

    Hope this helps a bit.

提交回复
热议问题