Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Last active August 25, 2022 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrhynas/7d748f690acd640d7eae65a11bae052b to your computer and use it in GitHub Desktop.
Save jayrhynas/7d748f690acd640d7eae65a11bae052b to your computer and use it in GitHub Desktop.
@dynamicMemberLookup
struct Builder<Object> {
let object: Object
init(_ object: Object) {
self.object = object
}
subscript<T>(dynamicMember keyPath: WritableKeyPath<Object, T>) -> (T) -> Builder<Object> {
return {
var copy = object
copy[keyPath: keyPath] = $0
return Builder(copy)
}
}
func call(_ work: (Object) -> Void) -> Builder<Object> {
work(object)
return self
}
}
// configure an existing object
let view1 = UIView()
Builder(view1)
.backgroundColor(.white)
.call { $0.addSubview(UIView()) }
.isExclusiveTouch(true)
// create a new object
let view2 = Builder(UIView())
.backgroundColor(.black)
.object
@jayrhynas
Copy link
Author

jayrhynas commented Aug 25, 2022

The Setter type is required because we can't add @discardableResult to closures

@k-marin
Copy link

k-marin commented Aug 25, 2022

very good

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