如何符合协议的变量集&得到? [英] How to conform to a protocol's variables' set & get?

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

问题描述

我正在研究协议以及如何遵守这些协议.

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:

类型男孩"不符合协议人类"

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.

推荐答案

来自快速参考:

财产要求

...
协议没有指定该属性是存储属性还是计算属性,它仅指定所需的属性名称和类型.
...
属性要求始终声明为变量属性,并以var关键字为前缀.在类型声明之后,通过写{ get set }来指示可获取属性和可设置属性,通过写{ 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
    }
}

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

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
}

或具有同时具有getem和setter的计算属性:

or with a computed property which has both getter and setter:

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

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

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