Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active Aug 24, 2021
Embed
What would you like to do?
Combined: A type composed of other types (potential alternative to my Partial<T> type)
@dynamicMemberLookup
struct Combined<A, B> {
private let a: A
private let b: B
init(a: A, b: B) { (self.a, self.b) = (a, b) }
subscript<T>(dynamicMember keyPath: KeyPath<A, T>) -> T {
return a[keyPath: keyPath]
}
subscript<T>(dynamicMember keyPath: KeyPath<B, T>) -> T {
return b[keyPath: keyPath]
}
}
struct Foo: Equatable { let fooValue: String }
struct Bar: Equatable { let barValue: String }
struct Baz: Equatable { let bazValue: String }
typealias Step1 = Combined<Void, Foo>
typealias Step2 = Combined<Step1, Bar>
typealias Step3 = Combined<Step2, Baz>
let step1 = Step1(a: (), b: .init(fooValue: "foo"))
step1.fooValue // foo
let step2 = Step2(a: step1, b: .init(barValue: "bar"))
step2.fooValue // foo
step2.barValue // bar
let step3 = Step3(a: step2, b: .init(bazValue: "baz"))
step3.fooValue // foo
step3.barValue // bar
step3.bazValue // baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment