class X { static let global: [String:String] = [ "x":"x data","y":"y data","z":"z data" ] func test(){ let type = "x" var data:String = X.global[type]! } }
我收到错误:可选类型’String?’的值没有打开.
我为什么需要使用!在X.global [type]之后?我在字典中没有使用任何可选项?
编辑:
即使该类型可能不存在X.global [type],强制解包仍会在运行时崩溃.更好的方法可能是:
if let valExist = X.global[type] { }
但是Xcode通过暗示可选类型给了我错误的想法.
解决方法
字典访问器返回其值类型的可选项,因为它不“知道”运行时字典中是否存在某些键.如果它存在,则返回相关值,但如果不存在则返回nil.
You can also use subscript Syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists,a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key,the subscript returns an optional value containing the existing value for that key. Otherwise,the subscript returns nil…
为了正确处理这种情况,你需要打开返回的可选项.
有几种方法:
选项1:
func test(){ let type = "x" if var data = X.global[type] { // Do something with data } }
选项2:
func test(){ let type = "x" guard var data = X.global[type] else { // Handle missing value for "type",then either "return" or "break" } // Do something with data }
选项3:
func test(){ let type = "x" var data = X.global[type] ?? "Default value for missing keys" }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。