有没有办法将协议属性声明为私有? [英] Is there a way to declare protocol property as private?

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

问题描述

我想遵守协议,并隐藏要访问的符合协议的属性(将它们声明为 private).

I want to conform to a protocol, as well as to hide its conformed properties to be accessed (declare them as private).

考虑以下事项:

protocol P {
    var value: String { get }

    init(value: String)
}

class C: P {
    var value: String

    required init(value: String) {
        self.value = value
    }
}

我会创建一个 C 对象:

I would create a C object:

let myObject = C(value: "Hello World")
myObject.value = "New Value"

基于此,我有两个问题:

Based on that I have 2 questions:

现在,如果我尝试将 value 声明为私有:

Now, if I tried to declare value as private:

private var value: String { get }

编译器会抛出错误:

'private' 修饰符不能在协议中使用

'private' modifier cannot be used in protocols

带有将 private 替换为 internal 的修复建议.

with a fix suggestion to replace the private with internal.

如何通过说 myObject.value 来阻止访问 value?如果没有办法,这个限制的原因是什么?

How can I prevent value from being accessible by saying myObject.value? if there is no way, what's the reason of this limitation?

推荐答案

符合

protocol P {
    var value: String { get }

    init(value: String)
}

需要具有默认访问权限的可获取属性 value.如果写访问符合类中的属性应仅限于类本身然后你可以在 Swift readonly external, readwrite internal property 中声明它:

requires a gettable property value with default access. If write access to the property in the conforming class should be restricted to the class itself then you can declare it as in Swift readonly external, readwrite internal property:

class C: P {
    private(set) var value: String

    required init(value: String) {
        self.value = value
    }
}

let myObject = C(value: "Hello World")
print(myObject.value) // OK
myObject.value = "New Value" // Error: Cannot assign to property: 'value' setter is inaccessible

如果该属性只应在初始化程序中设置,则将其设置为常量:

And if the property should only be set in initializers then make it a constant:

class C: P {
    let value: String

    required init(value: String) {
        self.value = value
    }
}

let myObject = C(value: "Hello World")
print(myObject.value) // OK
myObject.value = "New Value" // Error: Cannot assign to property: 'value' is a 'let' constant

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

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