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 throws the following error:
type 'Boy' does not conform to protocol 'Human'
However writing as below won't have any errors:
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.
EDIT: make sure you see Imanou's answer here. It greatly explains the different scenarios.
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 thevar
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 ...
}
}
}