kri*_*l99 26 arrays subscript swift
在我的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)"
}
Run Code Online (Sandbox Code Playgroud)
mat*_*att 35
问题是您使用的是NSArray:
myQuestionsArray = NSArray(contentsOfFile: path)
Run Code Online (Sandbox Code Playgroud)
这意味着这myQuestionArray是一个NSArray.但NSArray没有关于其元素的类型信息.因此,当你到达这一行时:
let currentQuestionDict = myQuestionsArray!.objectAtIndex(count)
Run Code Online (Sandbox Code Playgroud)
... Swift没有类型信息,必须制作currentQuestionDictAnyObject.但你不能下标AnyObject,所以表达式就像currentQuestionDict["choice1"]无法编译.
解决方案是使用Swift类型.如果你知道究竟currentQuestionDict是什么,请输入该类型.至少,因为你似乎相信它是一本字典,所以把它作为一本; 输入它[NSObject:AnyObject](如果可能的话,更具体).你可以用几种方式做到这一点; 一种方法是在创建变量时进行转换:
let currentQuestionDict =
myQuestionsArray!.objectAtIndex(count) as! [NSObject:AnyObject]
Run Code Online (Sandbox Code Playgroud)
简而言之,如果你可以避免使用NSArray和NSDictionary(你通常可以避免它).如果从Objective-C收到一个,请将其输入为实际内容,以便Swift可以使用它.
["Key"]导致此错误.新的Swift更新,您应该objectForKey用来获取您的价值.在你的情况下,只需将你的代码更改为;
if let button1Title = currentQuestionDict.objectForKey("choice1") as? String {
button1.setTitle("\(button1Title)", forState: UIControlState.Normal)
}
Run Code Online (Sandbox Code Playgroud)