【发布时间】:2017-07-08 10:03:31
【问题描述】:
我正在尝试通过一个扩展在 UIView 上创建一个 set 方法,该扩展允许我通过新的 Swift 4 KeyPaths 设置颜色。如果我执行以下操作,我会收到错误 Cannot assign to immutable expression of type 'UIColor?'
extension UIView {
func set(color: UIColor, forKeyPath path: KeyPath<UIView, UIColor?>) {
self[keyPath: path] = color // ???? Error: Cannot assign to immutable expression of type 'UIColor?'
}
}
view.set(color: .white, forKeyPath: \.backgroundColor)
如果我在扩展之外使用它,它可以正常工作:
let view = UIView()
let path = \UIView.backgroundColor
view[keyPath: path] = .white // Works fine
同样使用旧样式的 KeyPath 也可以正常工作:
extension UIView {
func set(color: UIColor, forKeyPath path: String) {
self.setValue(color, forKey: path)
}
}
view.set(color: .white, forKeyPath: #keyPath(UIView.backgroundColor))
感谢您的帮助。
【问题讨论】: