【发布时间】: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)编译。答案似乎是正确的。我的观点是,即使你让它编译,那么你的 setterkeyboardLabel = newValue的 实现 也不会按预期工作。
标签: swift protocols private swift-protocols swift-extensions