Skip to content

Instantly share code, notes, and snippets.

@0xLeif
Last active August 21, 2020 22:21
Show Gist options
  • Save 0xLeif/1f7a5f6bd22b5a3252bac8057244896f to your computer and use it in GitHub Desktop.
Save 0xLeif/1f7a5f6bd22b5a3252bac8057244896f to your computer and use it in GitHub Desktop.
KeyPath
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)
@0xLeif
Copy link
Author

0xLeif commented Aug 21, 2020

CleanShot 2020-08-21 at 17 20 26

error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
dumb + .string - "Hello!" + .double - 3.14 + .array - [1, 43, 6, true]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment