swift - 如何使用私有(private)集扩展协议(protocol)?

标签 swift protocols private swift-protocols swift-extensions

我正在编写一个带有只读标签的协议(protocol)。我想扩展它并给它一个默认实现,其中符合类型是 UITextView

代码:

protocol CountingView {

    var keyboardLabel : UILabel {get}   
}

extension CountingView where Self : UITextView {

    var keyboardLabel : UILabel {
        get {
            let label = UILabel()
            label.textColor = UIColor.white
            label.translatesAutoresizingMaskIntoConstraints = false

            return label
        }
        private (set) {
            keyboardLabel = newValue
        }
    }
}

但是,当我在 set 之前添加 private 时,出现以下错误。

Expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition

我查找了其他有这个错误的问题,但没有找到与我相关的问题。

最佳答案

你只是把 private 放在了错误的地方:

private(set) var keyboardLabel : UILabel {
    get {
        let label = UILabel()
        label.textColor = UIColor.white
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }
    set {
        keyboardLabel = newValue
    }
}

关于swift - 如何使用私有(private)集扩展协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115637/

相关文章:

ios - 显示 UItableViewcell 选择

swift - 符合具有通用功能的协议(protocol)的变量

arrays - Swift:在扩展中声明一个类型的数组符合协议(protocol)

clojure - 将 core.logic 扩展到自定义类型

javascript - 使用私有(private)成员复制 javascript 对象

ios - 在 Swift 中强制自定义 AVSpeech 和 AVSpeechUtterance 中单词的发音

arrays - 为什么 count 返回 Collection 和 Array 的不同类型?

oop - 为什么协议(protocol)的关联类型在 Swift 中不使用泛型语法?

C++ 保留对象列表并通过另一个函数调用构造函数

javascript - 在运行时选择私有(private)字段