Skip to content

Instantly share code, notes, and snippets.

@wddwycc
Created June 8, 2019 06:52
Show Gist options
  • Save wddwycc/bd8edfab02e3b999b2374f211ac064a3 to your computer and use it in GitHub Desktop.
Save wddwycc/bd8edfab02e3b999b2374f211ac064a3 to your computer and use it in GitHub Desktop.
Lens with @dynamicMemberLookup in Swift5.1
import Foundation
struct Lens<Whole, Part> {
let view: (Whole) -> Part
let set: (Part, Whole) -> Whole
}
protocol LensCompatible {}
@dynamicMemberLookup
struct LensProxy<Base: LensCompatible> {
subscript<T>(dynamicMember keyPath: WritableKeyPath<Base, T>) -> Lens<Base, T> {
Lens<Base, T>(
view: { $0[keyPath: keyPath] },
set: { part, whole in
var copy = whole
copy[keyPath: keyPath] = part
return copy
})
}
}
extension LensCompatible {
static var lens: LensProxy<Self> {
return LensProxy()
}
}
// Apply
struct Location {
var name: String
}
extension Location: LensCompatible {}
let locationNameLens = Location.lens.name // Lens<Location, String>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment