展开Plist并查找对象

时间:2014-12-13 12:35:11

标签: arrays swift plist

试图将目标c转换为快速变得非常沮丧。我有以下代码适用于目标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];
}

但我似乎无法让它迅速发挥作用。我可以使用

取出plist的内容
var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")

但是我看不到swift中有一个与objectAtIndex相当的东西。如果我尝试以下操作,我会收到一条错误消息,告知“字符串没有名为subcript的成员”,这显然意味着我需要解开路径。

let firstQuestion = path[0]

2 个答案:

答案 0 :(得分:0)

您正在调用的方法(如NSBundle.mainBundle().pathForResource)会返回选项,因为它们可能会失败。在Objective-C中,失败由nil表示,而Swift使用选项。

所以在你的例子中:

var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")

path的类型为Optional<String>(或String?),而不是String类型。 Optional<String>没有下标方法(即不支持[ ])。要在其中使用字符串,您必须检查可选项是否包含值(即对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
}

您可以在the Swift book的介绍中了解有关选项的更多信息。

答案 1 :(得分:0)

您还没有从Objective-C翻译整个第一行。您缺少对NSMutableArray的调用,该调用根据文件的内容创建数组。原始代码令人困惑,因为它确实是问题时调用文件path的内容。试试这个:

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
    }
}