Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

ios - Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'

ERROR:

Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'

CODE:

  func getApple(appleId: String) {
     var apples = userDefaults.dictionaryForKey("apples_array")
     println(apples[appleId])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...