ios – 如何符合协议变量的设置和获取?

前端之家收集整理的这篇文章主要介绍了ios – 如何符合协议变量的设置和获取?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在玩协议以及如何符合它们. @H_404_2@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’

但是写下面的内容不会有任何错误

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

当你也可以设置一个变量时,我不明白其中的区别,也不知道究竟需要实现什么.我查看了不同的问题和教程,但他们只是写作并没有任何更深入的解释.

编辑:
确保你看到Imanou的回答here.它极大地解释了不同的场景.

解决方法

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 }.

在你的情况下

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

是一个只能得到的计算属性,它是一个
快捷方式

@H_404_2@var height: Int { get { return 5 } }

但人类协议需要一个可获取和可设置的属性.
您可以符合存储的变量属性(如您所注意到的):

@H_404_2@struct Boy: Human { var height = 5 }

或者具有同时具有getter和setter的计算属性

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

猜你在找的iOS相关文章