Swift 中下标的使用不明确

Ambiguous Use of Subscript in Swift

我的 Swift 代码中一直出现 "ambiguous use of subscript," 错误。我不知道是什么导致了这个错误。它只是随机弹出。这是我的代码:

if let path = NSBundle.mainBundle().pathForResource("MusicQuestions", ofType: "plist") {
    myQuestionsArray = NSArray(contentsOfFile: path)
}

var count:Int = 1
let currentQuestionDict = myQuestionsArray!.objectAtIndex(count)

if let button1Title = currentQuestionDict["choice1"] as? String {
    button1.setTitle("\(button1Title)", forState: UIControlState.Normal)
}

if let button2Title = currentQuestionDict["choice2"] as? String {
    button2.setTitle("\(button2Title)", forState: UIControlState.Normal)
}

if let button3Title = currentQuestionDict["choice3"] as? String {
    button3.setTitle("\(button3Title)", forState: UIControlState.Normal)
}
if let button4Title = currentQuestionDict["choice4"] as? String {
    button4.setTitle("\(button4Title)", forState: UIControlState.Normal)
}

if let question = currentQuestionDict["question"] as? String!{
    questionLabel.text = "\(question)"
}

问题是你正在使用 NSArray:

myQuestionsArray = NSArray(contentsOfFile: path)

这意味着 myQuestionArray 是一个 NSArray。但是 NSArray 没有关于其元素的类型信息。因此,当您到达此行时:

let currentQuestionDict = myQuestionsArray!.objectAtIndex(count)

...Swift 没有类型信息,必须使 currentQuestionDict 成为 AnyObject。但是你不能下标 AnyObject,所以像 currentQuestionDict["choice1"] 这样的表达式不能编译。

解决方案是使用 Swift 类型。如果您知道 currentQuestionDict 的真正含义,请将其输入为该类型。至少,既然你似乎相信它是一本字典,那就把它变成一本吧;将其键入 [NSObject:AnyObject](如果可能,更具体)。您可以通过多种方式做到这一点;一种方法是在创建变量时进行强制转换:

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

简而言之,如果可以避免的话,永远不要使用 NSArray 和 NSDictionary(通常可以避免)。如果您从 Objective-C 收到一个,请按实际情况键入它,以便 Swift 可以使用它。

["Key"] 导致此错误。新 Swift 更新,你应该使用 objectForKey 来获取你的值。在你的情况下,只需将你的代码更改为 ;

if let button1Title = currentQuestionDict.objectForKey("choice1") as? String {
    button1.setTitle("\(button1Title)", forState: UIControlState.Normal)
}

这是我用来解决错误的代码:

    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

希望对您有所帮助!