@dynamicMemberLookupを利用してデータ構造を作りつつ、syntaxはシンプルに

Updated
Mar 5, 2021 8:50 AM
Created
Mar 5, 2021 8:49 AM
Tags
Swift
Keywords

@dynamicMemberLookup
struct MemberBox<T> {
  
  let source: T
  
  subscript<U>(dynamicMember keyPath: KeyPath<T, U>) -> U {
    source[keyPath: keyPath]
  }
  
}

struct State {
  var name: String = ""
}

let box = MemberBox.init(source: State())

box.name