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

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

概述我正在玩协议以及如何符合它们. protocol Human { var height: Int {get set} }struct boy : Human { var height: Int {return 5} // error!} 我正在尝试学习不同的方法来实现set和get. 但是,上面的代码会引发以下错误: type ‘boy’ does not 我正在玩协议以及如何符合它们.
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.它极大地解释了不同的场景.

解决方法 从 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 }.

在你的情况下

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

以上是内存溢出为你收集整理的ios – 如何符合协议变量的设置和获取?全部内容,希望文章能够帮你解决ios – 如何符合协议变量的设置和获取?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1103587.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存