LoginSignup
4
4

More than 3 years have passed since last update.

@dynamicMemberLookupとKeyPathで不要なcomputed propertyを減らす

Posted at

こちらのプロポーザルにより、Swift5.1から @dynamicMemberLookupとKeyPathを組み合わせることで、以前よりも安全にダイナミックなメンバーにアクセスすることができるようになりました。 

以下のサンプルでは、Testという構造体のcolorのcgColorを直接取得したい場合、これまではcomputed propertyを用意する必要があり、それごとにプロパティを用意してあげる必要がありましたが、KeyPathベースのdynamicMemberLookupを使うことにより、 Test構造体から直接 colorの全てのプロパティにアクセスすることができるようになります。

@dynamicMemberLookup
struct Test {
    var color = UIColor.red

    subscript<T>(dynamicMember keyPath: KeyPath<UIColor, T>) -> T {
        color[keyPath: keyPath]
    }
}

// Equivalent
Test().color.cgColor
Test().cgColor

参考

https://developer.apple.com/videos/play/wwdc2019/415/ (20:24付近から)
https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md
https://github.com/apple/swift-evolution/blob/master/proposals/0252-keypath-dynamic-member-lookup.md

4
4
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
4
4