在我的Swift代码中,我一直收到“下标的歧义用法”的错误。我不知道是什么导致了这个错误。它只是随机出现的。下面是我的代码:
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)"
}发布于 2015-11-11 09:20:24
问题是您使用的是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可以使用它。
发布于 2016-03-23 20:00:04
"Key"导致了此错误。新的Swift更新,您应该使用objectForKey来获取您的价值。在您的情况下,只需将您的代码更改为;
if let button1Title = currentQuestionDict.objectForKey("choice1") as? String {
button1.setTitle("\(button1Title)", forState: UIControlState.Normal)
}发布于 2016-04-02 14:24:21
这是我用来解决这个错误的代码:
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希望这能有所帮助!
https://stackoverflow.com/questions/33642059
复制相似问题