【问题标题】:How can I extend protocol with private set?如何使用私有集扩展协议?
【发布时间】:2017-05-22 14:34:23
【问题描述】:

我正在编写一个带有只读标签的协议。我想扩展它并给它一个默认实现,其中符合类型是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 时,出现以下错误。

需要“get”、“set”、“willSet”或“didSet”关键字来启动 访问器定义

我查找了其他与此错误相关的问题,但没有发现它们与我的相关。

【问题讨论】:

  • 扩展无法添加存储的属性。你的 setter 会递归地调用自己。比较stackoverflow.com/questions/44063181/…
  • @MartinR 嗯。好的。你的意思是这里的答案不正确?
  • 好吧,您的问题是如何使private(set) 编译。答案似乎是正确的。我的观点是,即使你让它编译,那么你的 setter keyboardLabel = newValue实现 也不会按预期工作。

标签: swift protocols private swift-protocols swift-extensions


【解决方案1】:

你只是把私人放在错误的地方:

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

        return label
    }
    set {
        keyboardLabel = newValue
    }
}

【讨论】:

  • 所以你每次调用getter方法的时候都会创建一个新标签?它是如何工作的??
【解决方案2】:

只需将您的计算属性 private 设为:

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

        return label
    }

    set {
        keyboardLabel = newValue
    }
}

【讨论】:

  • 天哪,你每次调用getter的时候都会创建一个新的label对象?
  • @Itachi,这不是问题本身。有更好的方法来做到这一点。但是 OP 想知道private(set) 的一般工作原理。
猜你喜欢
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
相关资源
最近更新 更多