Skip to content

Instantly share code, notes, and snippets.

@grdsdev
Last active July 17, 2020 10:30
Show Gist options
  • Select an option

  • Save grdsdev/dc55c9ac383e4796162df220f49af627 to your computer and use it in GitHub Desktop.

Select an option

Save grdsdev/dc55c9ac383e4796162df220f49af627 to your computer and use it in GitHub Desktop.
import UIKit
@dynamicMemberLookup
public struct Builder<Base> {
private let _build: () -> Base
public init(_ build: @escaping () -> Base) {
self._build = build
}
public init(_ base: Base) {
self._build = { base }
}
public subscript<Value>(dynamicMember keyPath: WritableKeyPath<Base, Value>) -> (Value) -> Builder<Base> {
return { [build] value in
Builder {
var object = build()
object[keyPath: keyPath] = value
return object
}
}
}
public func build() -> Base {
_build()
}
}
postfix operator ..
@discardableResult
public postfix func .. <T>(object: T) -> Builder<T> {
Builder(object)
}
@grdsdev
Copy link
Author

grdsdev commented Jul 17, 2020

Usage example

let label = UILabel()..
    .text("Nice!")
    .textColor(.red)
    .build()

struct User {
    var name: String = ""
    var email: String = ""
}

let user = User()..
    .name("Guilherme")
    .email("[email protected]")
    .build()

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