如何使协议变量的设置和放大符合得到? [英] How can you conform protocol variables' set & get?

查看:137
本文介绍了如何使协议变量的设置和放大符合得到?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩协议以及如何符合它们。

I'm playing around with protocols and how to conform to them.

protocol Human {    
    var height: Int {get set}    
}

struct boy : Human { 
    var height: Int  {return 5} // error!
}

我正在尝试学习不同的方法来实现set和get。
但是上面的代码会抛出以下错误:

I'm trying to learn different ways that I can implement set and get. However the code above throws the following error:


类型'boy'不符合协议'Human'

type 'boy' does not conform to protocol 'Human'

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

However writing as below won't have any errors:

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

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

I don't understand the difference nor what exactly needs to be implemented when you can also set a variable. I looked into different questions and tutorials but they all just write and go without any deeper explanation.

编辑:
确保看到Imanou的答案此处。它大大解释了不同的场景。

make sure you see Imanou's answer here. It greatly explains the different scenarios.

推荐答案

来自 Swift Reference


属性要求

...

协议未指定属性是存储属性还是属性computed属性 - 它只指定所需的属性名称和类型。

...

属性要求总是声明为变量属性,前缀为 var 关键字。在类型声明后写入 {get set} 表示gettable和可设置属性,并通过编写 {get}

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

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

is a computed property which can only be get, it is a shortcut for

var height: Int {
    get {
        return 5
    }
}

但是协议需要一个可获取和可设置的属性。
您可以符合存储的变量属性(如您所见):

But the Human protocol requires a property which is gettable and settable. You can either conform with a stored variable property (as you noticed):

struct Boy: Human { 
    var height = 5
}

或with a具有 getter和setter的计算属性:

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

这篇关于如何使协议变量的设置和放大符合得到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆