Created
June 8, 2019 06:52
-
-
Save wddwycc/bd8edfab02e3b999b2374f211ac064a3 to your computer and use it in GitHub Desktop.
Lens with @dynamicMemberLookup in Swift5.1
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 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