Sam*_*Sam 0 swift swift-dictionary
我有一个可选值,我想用它来索引字典。
我怎样才能做到这一点而不必用if let/ '弄脏'我的代码else?
例如
if
let key = type(of: self).notificationValueKeys[notification.name],
let value = notification.userInfo?[key] {
self.value = value
} else {
self.value = nil
}
Run Code Online (Sandbox Code Playgroud)
一种优雅的方法是使用扩展Dictionary来允许下标 ( []) 运算符Dictionary使用可选键:
/**
convenience subscript operator for optional keys
- parameter key
- returns: value or nil
*/
subscript(key: Key?) -> Value? {
guard let key = key else { return nil }
return self[key]
}
Run Code Online (Sandbox Code Playgroud)
这允许上面的代码变成:
let key = type(of: self).notificationValueKeys[notification.name]
let value = notification.userInfo?[key]
self.value = value
Run Code Online (Sandbox Code Playgroud)
哪里let value现在是可选的。