protocol Human {
var height: Int {get set}
}
struct boy : Human {
var height: Int {return 5} // error!
}
我正在尝试学习不同的方法来实现set和get.
但是,上面的代码会引发以下错误:
type ‘boy’ does not conform to protocol ‘Human’
但是写下面的内容不会有任何错误:
struct boy : Human {
var height = 5 // no error
}
当你也可以设置一个变量时,我不明白其中的区别,也不知道究竟需要实现什么.我查看了不同的问题和教程,但他们只是写作并没有任何更深入的解释.
编辑:
确保你看到Imanou的回答here.它极大地解释了不同的场景.
解决方法
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 }.
在你的情况下
var height: Int {return 5} // error!
是一个只能得到的计算属性,它是一个
快捷方式
var height: Int {
get {
return 5
}
}
但人类协议需要一个可获取和可设置的属性.
您可以符合存储的变量属性(如您所注意到的):
struct Boy: Human {
var height = 5
}
或者具有同时具有getter和setter的计算属性:
struct Boy: Human {
var height: Int {
get {
return 5
}
set(newValue) {
// ... do whatever is appropriate ...
}
}
}