Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import Foundation
  2.  
  3. public class AnyMap<Left, Right> {
  4. public func map(_ left: Left, to right: inout Right) {}
  5. public func reversed() -> AnyMap<Right, Left>? { return nil }
  6. }
  7.  
  8. public final class KeyPathMap<Left, Right, Value>: AnyMap<Left, Right> {
  9. public let from: KeyPath<Left, Value>
  10. public let to: WritableKeyPath<Right, Value>
  11.  
  12. public init(from: KeyPath<Left, Value>, to: WritableKeyPath<Right, Value>) {
  13. self.from = from
  14. self.to = to
  15. }
  16.  
  17. public override func map(_ left: Left, to right: inout Right) {
  18. right[keyPath: to] = left[keyPath: from]
  19. }
  20.  
  21. public override func reversed() -> AnyMap<Right, Left>? {
  22. guard let key = from as? WritableKeyPath<Left, Value> else { return nil }
  23. return KeyPathMap<Right, Left, Value>(from: to, to: key)
  24. }
  25. }
  26.  
  27. public final class GroupMap<Left, Right>: AnyMap<Left, Right> {
  28. var maps: [AnyMap<Left, Right>] = []
  29.  
  30. public override func map(_ left: Left, to right: inout Right) {
  31. maps.forEach { $0.map(left, to: &right) }
  32. }
  33.  
  34. public func add<T>(from: KeyPath<Left, T>, to: WritableKeyPath<Right, T>) {
  35. maps.append(KeyPathMap(from: from, to: to))
  36. }
  37.  
  38. public override func reversed() -> AnyMap<Right, Left>? {
  39. let maps = self.maps.compactMap { $0.reversed() }
  40. let group = GroupMap<Right, Left>()
  41. group.maps = maps
  42. return group
  43. }
  44. }
  45.  
  46. struct AdminUser {
  47. var login: String
  48. }
  49.  
  50. struct User: Codable {
  51. var name: String
  52. }
  53.  
  54. var user = User(name: "X")
  55. var admin = AdminUser(login: "none")
  56.  
  57. let mapper = GroupMap<User, AdminUser>()
  58. mapper.add(from: \.name, to: \.login)
  59.  
  60. mapper.map(user, to: &admin)
  61. admin.login
  62.  
  63. admin.login = "New"
  64. mapper.reversed()!.map(admin, to: &user)
  65. user.name
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement