[英]Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'
ERROR: 错误:
Cannot subscript a value of type '[NSObject : AnyObject]?'
不能下标'[NSObject:AnyObject]类型的值吗? with an index of type 'String'
索引类型为'String'
CODE: 码:
func getApple(appleId: String) {
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples[appleId])
Should be: 应该:
var apples = userDefaults.dictionaryForKey("apples_array")
println(apples?[appleId])
The issue here is that type [NSObject : AnyObject]?
这里的问题是类型
[NSObject : AnyObject]?
implies an optional type, which means you're attempting to call a subscript on what is essentially an enum. 暗示一个可选类型,这意味着你试图调用一个基本上是enum的下标。 When you try to do this, there's no subscript declared, so the system chokes.
当你尝试这样做时,没有声明下标,所以系统会窒息。
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. 强制解包,但如果
apples
为零则会崩溃。 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. 这样,apples不再是可选的,它将始终具有下标语法。 No unwrapping necessary.
没有打包必要。
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])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.