Created
July 8, 2020 12:27
-
-
Save mugbug/3ee4528aab1223d29f28aaac05a1ddcb to your computer and use it in GitHub Desktop.
Generic Builder DSL in Swift
This file contains hidden or 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
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) | |
} | |
} |
This file contains hidden or 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 | |
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