Skip to content

Instantly share code, notes, and snippets.

@yesleon
Created June 26, 2019 08:30
Show Gist options
  • Save yesleon/2d21cc7b14a6b10a2186931999a4c147 to your computer and use it in GitHub Desktop.
Save yesleon/2d21cc7b14a6b10a2186931999a4c147 to your computer and use it in GitHub Desktop.
A simple struct for enabling fluent interface writing style in >= Swift 5.1.
@dynamicMemberLookup
public struct FluentInterface<Root> {
public let root: Root
public subscript<Value>(dynamicMember keyPath: WritableKeyPath<Root, Value>) -> (Value) -> Self {
var root = self.root
return { newValue in
root[keyPath: keyPath] = newValue
return FluentInterface(root: root)
}
}
}
postfix operator +
public postfix func + <T>(lhs: T) -> FluentInterface<T> {
return FluentInterface(root: lhs)
}
postfix operator -
extension FluentInterface {
@discardableResult
public static postfix func - (lhs: FluentInterface) -> Root {
return lhs.root
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment