Swift Optional Dictionary [String: String?] unwrapping error

泄露秘密 提交于 2019-12-11 23:33:51

问题


So here I have a basic setup

var preferenceSpecification = [String : String?]()
preferenceSpecification["Key"] = "Some Key"
preferenceSpecification["Some Key"] = nil
preferenceSpecification["DefaultValue"] = "Some DefaultValue"
print(preferenceSpecification)
var defaultsToRegister = [String : String]()

if let key = preferenceSpecification["Key"], let defaultValueKey = preferenceSpecification["DefaultValue"] {
    defaultsToRegister[key] = preferenceSpecification[defaultValueKey]!
}

But the error points out where it demands that I force unwrap this, to be like this:

defaultsToRegister[key!] = preferenceSpecification[defaultValueKey!]!

Which doesn't make sense, because keyValue and defaultValue already are unwrapped


回答1:


When you extract a value from a dictionary like this using subscript

[String: String?]

you need to manage 2 levels of optional. The first one because the subscript returns an optional. The second one because the value of you dictionary is an optional String.

So when you write

if let value = preferenceSpecification["someKey"] {

}

you get value defined as an optional String.

Here's the code to fix that

if let
    optionalKey = preferenceSpecification["Key"],
    key = optionalKey,
    optionalDefaultValueKey = preferenceSpecification["DefaultValue"],
    defaultValueKey = optionalDefaultValueKey,
    value = preferenceSpecification[defaultValueKey] {
    defaultsToRegister[key] = value
}

Suggestions

  1. You should avoid force unwrapping as much as possible. Instead you managed to put 3 ! on a single line!
  2. You should also try to use better name for your constants and variables.


来源:https://stackoverflow.com/questions/39026275/swift-optional-dictionary-string-string-unwrapping-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!