Ambiguous Use of Subscript in Swift

后端 未结 3 1093
暗喜
暗喜 2020-12-10 10:12

I keep getting an error of \"ambiguous use of subscript,\" in my Swift code. I don\'t know what\'s causing this error. It just randomly popped up. Here\'s my code:



        
相关标签:
3条回答
  • 2020-12-10 11:03

    The problem is that you are using NSArray:

    myQuestionsArray = NSArray(contentsOfFile: path)
    

    This means that myQuestionArray is an NSArray. But an NSArray has no type information about its elements. Thus, when you get to this line:

    let currentQuestionDict = myQuestionsArray!.objectAtIndex(count)
    

    ...Swift has no type information, and has to make currentQuestionDict an AnyObject. But you can't subscript an AnyObject, so expressions like currentQuestionDict["choice1"] cannot compile.

    The solution is to use Swift types. If you know what currentQuestionDict really is, type it as that type. At the very least, since you seem to believe it is a dictionary, make it one; type it as [NSObject:AnyObject] (and more specific if possible). You can do this in several ways; one way is by casting when you create the variable:

    let currentQuestionDict = 
        myQuestionsArray!.objectAtIndex(count) as! [NSObject:AnyObject]
    

    In short, never use NSArray and NSDictionary if you can avoid it (and you can usually avoid it). If you receive one from Objective-C, type it as what it really is, so that Swift can work with it.

    0 讨论(0)
  • 2020-12-10 11:04

    ["Key"] has causing this error. New Swift update, you should use objectForKey to get your value. In you case just change the your code to ;

    if let button1Title = currentQuestionDict.objectForKey("choice1") as? String {
        button1.setTitle("\(button1Title)", forState: UIControlState.Normal)
    }
    
    0 讨论(0)
  • 2020-12-10 11:06

    This is the code I used to solve the error:

        let cell:AddFriendTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! AddFriendTableViewCell
    
        let itemSelection = items[indexPath.section] as! [AnyObject] //'items' is an array of NSMutableArrays, one array for each section
    
        cell.label.text = itemSelection[indexPath.row] as? String
    

    Hope this helps!

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