Skip to content

Instantly share code, notes, and snippets.

@mugbug
Created July 8, 2020 12:27
Show Gist options
  • Save mugbug/3ee4528aab1223d29f28aaac05a1ddcb to your computer and use it in GitHub Desktop.
Save mugbug/3ee4528aab1223d29f28aaac05a1ddcb to your computer and use it in GitHub Desktop.
Generic Builder DSL in Swift
infix operator ..: AdditionPrecedence
infix operator <-: MultiplicationPrecedence
struct Predicate<Element> {
let code: (Element) -> Element
func runCode(for element: Element) -> Element {
return code(element)
}
}
func <- <Element, T>(_ attribute: WritableKeyPath<Element, T>,
_ constant: T) -> Predicate<Element> {
return Predicate(code: { value in
var copy = value
copy[keyPath: attribute] = constant
return copy
})
}
protocol Builder {}
extension Builder {
@discardableResult
static func .. (_ element: Self,
_ predicate: Predicate<Self>) -> Self {
return element.with(predicate)
}
private func with(_ predicate: Predicate<Self>) -> Self {
return predicate.runCode(for: self)
}
}
import UIKit
class MyView: UIView {
lazy var label = UILabel()
.. \.text <- "Hello, World!"
.. \.font <- .systemFont(ofSize: 40)
.. \.textColor <- .white
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment