Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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に苦しんでください。

masakihori
非えんじにあ / 素人が雰囲気で書いてます
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away