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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...