2017-07-08 62 views
1

我想在UIView上创建一个设置方法,通过一个扩展来允许我通过新的Swift 4 KeyPaths设置颜色。如果我做了以下我得到的错误Cannot assign to immutable expression of type 'UIColor?'是否可以在扩展中通过Swift 4 KeyPaths在UIView上设置属性?

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)) 

感谢您的帮助。

回答

4

在你的独立例如,如果您选项 - 点选path你会看到它的声明是:

let path: ReferenceWritableKeyPath<UIView, UIColor?> 

所以它不只是一个KeyPathReferenceWritableKeyPath。点击ReferenceWritableKeyPath表明,它是:

支持从读取和写入所产生的 值参考语义的关键路径。

因此,您在extension中使用的KeyPath类型太严格,因为它不允许书写。

更改KeyPathReferenceWritableKeyPath通行证沿着正确的类型使得它的工作:

extension UIView { 
    func set(color: UIColor, forKeyPath path: ReferenceWritableKeyPath<UIView, UIColor?>) { 
     self[keyPath: path] = color 
    } 
} 

view.set(color: .white, forKeyPath: \.backgroundColor) // success! 
+0

那完美。 – Radther

相关问题