LoginSignup
6
0

More than 5 years have passed since last update.

[Swift 4.2] Dictionayでプロパティアクセス

Last updated at Posted at 2018-09-26

Swift 4.2 で Dynamic member look up というものが導入されました。

これを使うことで Key が String の Dictionary で下のコードのようにプロパティを使うように要素にアクセスできるようになります。

var hoge = ["hoge": "hoge"]

print(hoge.hoge)  // prints Optional("hoge")

print(hoge.piyo)  // prints nil
hoge.piyo = "piyo"
print(hoge.piyo)  // prints Optional("piyo")

まるでプロパティであるかのようですね!

以下ソース

@dynamicMemberLookup
protocol DynamicMemberLookupable {
  associatedtype ReturnValue
}

extension DynamicMemberLookupable  {
  subscript(dynamicMember member: String) -> ReturnValue {
    get { fatalError("oops!") }
    set { fatalError("oops!") }
  }
}

extension Dictionary: DynamicMemberLookupable where Key == String {
  typealias ReturnValue = Value?
  subscript(dynamicMember member: String) -> ReturnValue {
    get { return self[member] }
    set { self[member] = newValue }
  }
}

皆さんもこれを使ってtypoに苦しんでください。

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0