为什么在协议中声明readonly属性? [英] Why declare readonly property in protocol?

查看:124
本文介绍了为什么在协议中声明readonly属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们可以通过类或结构设置值,为什么在协议中声明readonly属性?我无法理解这个用法。
在The Swift Programming Book版本2.0中

Why declare readonly property in protocol if we can set value trough class or struct? I can not understand usage of this. In "The Swift Programming Book" version 2.0

如果协议只要求财产可以获取,那么任何一种财产都可以满足要求如果这对你自己的代码很有用,它对于属性也是有效的。

"If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it is valid for the property to be also settable if this is useful for your own code."

推荐答案

这样它就是不能从类/结构外部设置。想象一下,你的API返回了一个具有get和set属性的协议实例(在你的协议中),然后任何得到这个实例的人都可以设置值!

So that it's not settable from outside the class/struct. Imagine your API returned some instance of a protocol that has a get and set property (in your protocol), then anyone getting this instance would be able to set the value!

此外,get和set属性不能是常量:

Also get and set properties can't be constants:

protocol RWProt {
    var value : Int { get set }
}

// Error: Type 'Value' does not conform to protocol 'RWProt'
struct Value : RWProt {
    let value = 0
}

但这有效:

protocol Read {
    var value : Int { get }
}

struct Value : Read {
    var value = 0

    mutating func change() {
        value++
    }
}

协议只需要值可获取,因此获取协议属性不仅仅是获取或设置

The protocol only needs the value to be gettable, so get protocols properties are not get only but rather get or set

好的,这是另一个例子:

Okay, here is another example:

import Foundation

public protocol ExternalInterface {
    var value : Int { get }
}


private struct PrivateStuff : ExternalInterface {
    var value = 0

    mutating func doSomePrivateChangingStuff() {
        value = Int(arc4random())
    }
}



public func getInterfaceToPrivateStuff() -> ExternalInterface {
    var stuff = PrivateStuff()
    stuff.doSomePrivateChangingStuff()
    return stuff
}




// In another file:

let interfaceToSomethingICantChange = getInterfaceToPrivateStuff()

// error: cannot assign to property: 'value' is a get-only property
interfaceToSomethingICantChange.value = 0

这篇关于为什么在协议中声明readonly属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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