Swift可选字典[String:String?]展开错误 [英] Swift Optional Dictionary [String: String?] unwrapping error
本文介绍了Swift可选字典[String:String?]展开错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以这里我有一个基本设置
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!]!
这没有意义,因为 keyValue 和 defaultValue 已经解包
Which doesn't make sense, because keyValue and defaultValue already are unwrapped
推荐答案
使用下标从这样的字典中提取值时
When you extract a value from a dictionary like this using subscript
[String: String?]
您需要管理2个可选级别。第一个因为下标返回一个可选。第二个是因为字典的值是可选的字符串。
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.
因此,当您编写
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
- 您应尽可能避免强行展开。相反,您设法将3个
!
放在一行上。 - 您还应该尝试对常量和变量使用更好的名称。
- You should avoid force unwrapping as much as possible. Instead you managed to put 3
!
on a single line! - You should also try to use better name for your constants and variables.
这篇关于Swift可选字典[String:String?]展开错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文