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

我正在玩协议以及如何符合它们.
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 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...