A structure including backing value - AllOf structure in Swift

Updated
Jul 29, 2020 3:05 PM
Created
Jul 29, 2020 3:03 PM
Tags
Swift
Keywords

First look is here:

struct A {
  var name: String
}

struct B {
  var age: Int
}

typealias User = AllOf2<A, B>

extension User {
  init(name: String, age: Int) {
    self.init(.init(name: name), .init(age: age))
  }
}

var value = User(name: "Muuk", age: 18)

value.name
value.age

value.name = "J"
value.age = 32

How it works:

@dynamicMemberLookup
public struct AllOf2<O1, O2> {

  private var _o1: O1
  private var _o2: O2

  public init(_ o1: O1, _ o2: O2) {
    self._o1 = o1
    self._o2 = o2
  }

  public subscript <U>(dynamicMember keyPath: KeyPath<O1, U>) -> U {
    _o1[keyPath: keyPath]
  }

  public subscript <U>(dynamicMember keyPath: WritableKeyPath<O1, U>) -> U {
    _read {
      yield _o1[keyPath: keyPath]
    }
    _modify {
      yield &_o1[keyPath: keyPath]
    }
  }

  public subscript <U>(dynamicMember keyPath: KeyPath<O2, U>) -> U {
    _o2[keyPath: keyPath]
  }

  public subscript <U>(dynamicMember keyPath: WritableKeyPath<O2, U>) -> U {
    _read {
      yield _o2[keyPath: keyPath]
    }
    _modify {
      yield &_o2[keyPath: keyPath]
    }
  }
}