问题描述
错误:
代码:
func getApple(appleId: String) {
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples[appleId])
推荐答案
应该是:
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples?[appleId])
这里的问题是类型 [NSObject:AnyObject]?
意味着一个可选类型,这意味着你试图调用一个基本上是enum的下标。当你尝试这样做时,没有声明下标,所以系统会窒息。
The issue here is that type [NSObject : AnyObject]?
implies an optional type, which means you're attempting to call a subscript on what is essentially an enum. When you try to do this, there's no subscript declared, so the system chokes.
通过添加?
我们如果可能的话,打开这个值,然后调用下标。通过这种方式,系统可以查看类型 [NSObject:AnyObject]
以获取下标声明,一切正常。
By adding the ?
we're saying, unwrap this value if possible, and then call the subscript. This way the system infers to look on type [NSObject : AnyObject]
for subscript declarations and everything is ok.
您也可以使用!
强制解包,但如果 apples
为nil,则会崩溃。另一种可能的方法是:
You could also use !
to force an unwrap, but this will crash if apples
is nil. Another possible way to write this would be:
let apples = userDefaults.dictionaryForKey("apples_array") ?? [:]
println(apples[appleId])
这样,苹果就不再了可选,它将始终具有下标语法。不需要打包。
This way, apples is no longer optional and it will always have the subscript syntax. No unwrapping necessary.
这篇关于不能下标'[NSObject:AnyObject]类型的值吗?索引类型为'String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!