Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- public class AnyMap<Left, Right> {
- public func map(_ left: Left, to right: inout Right) {}
- public func reversed() -> AnyMap<Right, Left>? { return nil }
- }
- public final class KeyPathMap<Left, Right, Value>: AnyMap<Left, Right> {
- public let from: KeyPath<Left, Value>
- public let to: WritableKeyPath<Right, Value>
- public init(from: KeyPath<Left, Value>, to: WritableKeyPath<Right, Value>) {
- self.from = from
- self.to = to
- }
- public override func map(_ left: Left, to right: inout Right) {
- right[keyPath: to] = left[keyPath: from]
- }
- public override func reversed() -> AnyMap<Right, Left>? {
- guard let key = from as? WritableKeyPath<Left, Value> else { return nil }
- return KeyPathMap<Right, Left, Value>(from: to, to: key)
- }
- }
- public final class GroupMap<Left, Right>: AnyMap<Left, Right> {
- var maps: [AnyMap<Left, Right>] = []
- public override func map(_ left: Left, to right: inout Right) {
- maps.forEach { $0.map(left, to: &right) }
- }
- public func add<T>(from: KeyPath<Left, T>, to: WritableKeyPath<Right, T>) {
- maps.append(KeyPathMap(from: from, to: to))
- }
- public override func reversed() -> AnyMap<Right, Left>? {
- let maps = self.maps.compactMap { $0.reversed() }
- let group = GroupMap<Right, Left>()
- group.maps = maps
- return group
- }
- }
- struct AdminUser {
- var login: String
- }
- struct User: Codable {
- var name: String
- }
- var user = User(name: "X")
- var admin = AdminUser(login: "none")
- let mapper = GroupMap<User, AdminUser>()
- mapper.add(from: \.name, to: \.login)
- mapper.map(user, to: &admin)
- admin.login
- admin.login = "New"
- mapper.reversed()!.map(admin, to: &user)
- user.name
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement