Honey Honey - 9 days ago 7
Swift Question

How can you conform protocol variables' set & get?

I'm playing around with protocols and how to conform to them.

protocol Human {

var height: Int {get set}

}

struct boy : Human {
var height: Int {return 5} // error!
}


I'm trying to learn different ways that I can implement set and get.
However the code above gives an error that type 'boy' does not conform to protocol 'Human'

However I if I change it to

struct boy : Human {
var height = 5 // no error
}


I don't understand the difference nor what exactly needs to be implemented when you can also set a variable. I looked into different questions and tutorials but they all just write and go without any deeper explanation.

Answer

From the Swift Reference:

Property Requirements

...
The protocol doesn’t specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.
...
Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.

In your case

var height: Int  {return 5} // error!

is a computed property which can only be get, it is a shortcut for

var height: Int {
    get {
        return 5
    }
}

But the Human protocol requires a property which is gettable and settable. You can either conform with a stored variable property (as you noticed):

struct Boy: Human { 
    var height = 5
}

or with a computed property which has both getter and setter:

struct Boy: Human { 
    var height: Int {
        get {
            return 5
        }
        set(newValue) {
            // ... do whatever is appropriate ...
        }
    }
}
Comments