2017-07-08 67 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

相關問題