I'm trying to create a set method on UIView via an extension that will allow me to set a color via the new Swift 4 KeyPaths. If I do the following I get the error 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)
If I use this outside of an extension it works fine:
let view = UIView()
let path = \UIView.backgroundColor
view[keyPath: path] = .white // Works fine
Also using the old style of KeyPath works fine:
extension UIView {
func set(color: UIColor, forKeyPath path: String) {
self.setValue(color, forKey: path)
}
}
view.set(color: .white, forKeyPath: #keyPath(UIView.backgroundColor))
Thanks for any help.