0

我有一个可选值,我想用它来索引字典。

我怎样才能做到这一点而不必用if let/ '弄脏'我的代码else

例如

if
    let key = type(of: self).notificationValueKeys[notification.name],
    let value = notification.userInfo?[key] {

    self.value = value

} else {

   self.value = nil
}
4

1 回答 1

5

一种优雅的方法是扩展以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]
}

这使得上面的代码变成:

let key = type(of: self).notificationValueKeys[notification.name]
let value = notification.userInfo?[key]

self.value = value

现在在哪里let value是可选的。

于 2017-05-10T11:12:09.763 回答