I\'m playing around with protocols and how to conform to them.
protocol Human {
var height: Int { get set }
}
struct Boy: Human {
var height: In
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 thevarkeyword. 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 ...
}
}
}