Last active
August 21, 2020 22:21
-
-
Save 0xLeif/1f7a5f6bd22b5a3252bac8057244896f to your computer and use it in GitHub Desktop.
KeyPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
precedencegroup KeyPathPrecedence { | |
associativity: right | |
higherThan: MultiplicationPrecedence | |
} | |
infix operator ...: KeyPathPrecedence | |
func magic<T,E>(obj: inout T, path: ReferenceWritableKeyPath<T, E>, value: E) -> T { | |
obj[keyPath: path] = value | |
return obj | |
} | |
class KPObject<T,E> { | |
var obj: T | |
var path: ReferenceWritableKeyPath<T, E> | |
init(obj: T, path: ReferenceWritableKeyPath<T, E>) { | |
self.obj = obj | |
self.path = path | |
} | |
} | |
func ...<T,E>(obj: T, path: ReferenceWritableKeyPath<T, E>) -> KPObject<T, E> { | |
return KPObject(obj: obj, path: path) | |
} | |
func ...<T,E>(obj: KPObject<T,E>, path: ReferenceWritableKeyPath<T, E>) -> KPObject<T, E> { | |
obj.path = path | |
return obj | |
} | |
func +<T,E>(obj: KPObject<T,E>, value: E) -> T { | |
var o = obj.obj | |
magic(obj: &o, path: obj.path, value: value) | |
return o | |
} | |
var v = UIView() | |
let view: UIView = v ... \.backgroundColor + .red | |
((v ... \.layer.cornerRadius + 3) | |
... \.backgroundColor + .blue) | |
... \.layer.borderWidth + 6 | |
print(v.backgroundColor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
😭