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

前端 未结 2 746
孤城傲影
孤城傲影 2020-12-16 19:50

ERROR:

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

CODE:

  f         


        
相关标签:
2条回答
  • 2020-12-16 20:22

    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

    func getApple(appleId: String) {
         if let apples = userDefaults.dictionaryForKey("apples_array") {
            println(apples[appleId])
         }
    }
    
    0 讨论(0)
  • 2020-12-16 20:32

    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.

    0 讨论(0)
提交回复
热议问题