Arrays 展开Plist并查找对象

Arrays 展开Plist并查找对象,arrays,swift,plist,Arrays,Swift,Plist,试图将目标c翻译成swift时感到非常沮丧。我有以下代码用于目标c NSMutableArray *path = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sequence List" ofType:@"plist"]]; //Shuffle the array of questions numberSequenceList = [self shuffleArray:path

试图将目标c翻译成swift时感到非常沮丧。我有以下代码用于目标c

NSMutableArray *path = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sequence List" ofType:@"plist"]];

//Shuffle the array of questions
numberSequenceList = [self shuffleArray:path];

currentQuestion = currentQuestion + 1;

if (Round==1) {
    //Take first object in shuffled array as the first question
    NSMutableArray *firstQuestion = [[NSMutableArray alloc] initWithArray:[numberSequenceList objectAtIndex:0]];

    //Find question and populate text view
    NSString *string = [firstQuestion objectAtIndex:0];

    self.lblNumber.text = string;

    //Find and store the answer
    NSString *findAnswer = [firstQuestion objectAtIndex:1];

    Answer = [findAnswer intValue];
}
但我似乎无法在swift中实现这一点。我可以使用

var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")
但我看不出swift中有与objectAtIndex等价的东西。如果我尝试以下操作,我会收到一条错误消息,提示string没有名为subscript的成员,这显然意味着我需要展开路径

let firstQuestion = path[0]

您正在调用的方法,如NSBundle.mainBundle.pathForResource,返回optionals,因为它们可能会失败。在Objective-C中,该故障以零表示,而Swift使用选项

在你的例子中:

var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")
路径的类型是可选的还是字符串?而不是字符串类型。Optional没有下标方法,即不支持[]。要在中使用字符串,您必须检查可选项是否包含值,即对pathForResource的调用是否成功:

// the if let syntax checks if the optional contains a valid 
if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist”) {
    // use path, which will now be of type String
}
else {
    // deal with pathForResource failing
}

您可以在的简介中阅读有关optionals的更多信息。

您尚未翻译Objective-C中的整个第一行。您缺少对NSMutableArray的调用,该调用将根据文件内容创建数组。原始代码令人困惑,因为它在实际需要时调用文件路径的内容。试试这个:

if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist") {
    let questions = NSMutableArray(contentsOfFile: path)

    //Shuffle the array of questions
    numberSequenceList = self.shuffleArray(questions)

    currentQuestion = currentQuestion + 1

    if Round == 1 {
        //Take first object in shuffled array as the first question
        let firstQuestion = numberSequenceList[0] as NSArray

        //Find question and populate text view
        let string = firstQuestion[0] as NSString

        self.lblNumber.text = string

        //Find and store the answer
        let findAnswer = firstQuestion[1] as NSString

        Answer = findAnswer.intValue
    }
}

嗨,谢谢你的解释。但是,当我尝试使用if函数时,我现在收到一条消息,建议“Subscript不可用:无法使用int为字符串下标”。如何使用字符串中的第一个对象?firstmystring,由于字符串可能为空,因此返回可选值。或者mystring[mystring.startIndex]–字符串不是整数可索引的,因为它们不能保证是随机访问的,因为某些字符可以是不同的字节长度