RawRepresentable のままで Dictionary にアクセス
- Apple
- 開発
enum MyKey: String
{
case identifier
case colorCode
}
func process(_ dictionary: [String: Any])
{
let identifier = dictionary[MyKey.identifier.rawValue] as? String
let colorCode = dictionary[MyKey.colorCode.rawValue] as? Int
...
}
この .rawValue
を何度も書きたくなかったので extension を書いたという話。シンプルなコードなので誰が書いてもほぼ同じになりそう:
extension Dictionary
{
subscript<WrappedKey: RawRepresentable>(_ key: WrappedKey) -> Value? where WrappedKey.RawValue == Key
{
get { return self[key.rawValue] }
set { self[key.rawValue] = newValue }
}
}
let identifier = dictionary[MyKey.identifier] as? String
let colorCode = dictionary[MyKey.colorCode] as? Int
もちろん最初から [MyKey: Any]
にした方がきれいな状況であればその方がいいと思う。すっきりした勢いだけで書いた内容のない記事でした。
Share
リンクも共有もお気軽に。記事を書くモチベーションの向上に役立てます。