简体   繁体   English

为什么在协议中声明只读属性?

[英]Why declare readonly property in protocol?

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 在“ The Swift Programming Book” 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.” “如果协议仅要求一个属性是可获取的,则该要求可以由任何种类的属性来满足,并且如果该属性对您自己的代码有用,那么也可以对该属性进行设置是有效的。”

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! 假设您的API返回了某个具有get和set属性的协议实例(在您的协议中),那么任何获得此实例的人都可以设置该值!

Also get and set properties can't be constants: 而且get和set属性不能为常量:

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

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

This however works: 但是,这可行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM