xcode 无法为类型为“[NSObject : AnyObject]?”的值添加下标 带有'String'类型的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29994541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'
提问by hunterp
ERROR:
错误:
Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'
无法为类型为“[NSObject : AnyObject]?”的值添加下标 带有'String'类型的索引
CODE:
代码:
func getApple(appleId: String) {
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples[appleId])
回答by Logan
Should be:
应该:
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples?[appleId])
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.
这里的问题是 type[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.
通过添加?
我们所说的,如果可能的话解开这个值,然后调用下标。通过这种方式,系统推断出查看[NSObject : AnyObject]
下标声明的类型,一切正常。
You could also use !
to force an unwrap, but this will crash if apples
is nil. Another possible way to write this would be:
您也可以使用!
强制解包,但如果apples
为零,则会崩溃。另一种可能的写法是:
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.
这样,apples 不再是可选的,它将始终具有下标语法。无需拆包。
回答by sylvanaar
I think it is far more clear to use optional binding so that the println is only invoked when there is an actual value to print
我认为使用可选绑定要清楚得多,以便仅在有实际值要打印时才调用 println
func getApple(appleId: String) {
if let apples = userDefaults.dictionaryForKey("apples_array") {
println(apples[appleId])
}
}