从pList文件中随机显示一定数量的问题

时间:2016-01-28 03:16:49

标签: ios swift plist

我正在创建一个简单的测验应用。我在一个pList文件中存储了总共300个问题,并逐个显示问题。

现在,您如何从上述pList文件中仅获得一定数量的问题?例如,在我的300个问题的pList文件中,我在一个" go"中使用了所有问题。但是,有一种"练习模式"我只需要在300个问题的pList文件中随机获得100个问题。我该怎么做?

我已经看到了一些资源,但它们都在Objective-C中。

1 个答案:

答案 0 :(得分:0)

您可以使用此Nate Cook's中的answer shuffle扩展来对数组进行随机播放,并使用数组的前缀(n)方法从数组中选择所需数量的元素:

extension Array {
    var shuffled: [Element] {
        guard count > 1 else { return self }
        var elements = self
        for index in indices {
            let newIndex = Int(arc4random_uniform(UInt32(elements.count - index))) + index
             guard index != newIndex else { continue }
            swap(&elements[index], &elements[newIndex])
        }
        return elements
    }
}

测试:

let questions = Array(1...300).map{"Question \($0)"}
let shuffledQuestions = questions.shuffled
let firstOneHundred = shuffledQuestions.prefix(100)   // ["Question 163", "Question 77", "Question 262", "Question 292", "Question 229", "Question 199", "Question 93", "Question 35", "Question 19", "Question 65", "Question 107", "Question 142", "Question 174", "Question 172", "Question 240", "Question 131", "Question 274", "Question 252", "Question 214", "Question 285", "Question 185", "Question 219", "Question 51", "Question 267", "Question 170", "Question 6", "Question 55", "Question 67", "Question 115", "Question 148", "Question 137", "Question 139", "Question 116", "Question 259", "Question 24", "Question 283", "Question 273", "Question 147", "Question 17", "Question 16", "Question 97", "Question 2", "Question 74", "Question 215", "Question 184", "Question 84", "Question 247", "Question 73", "Question 37", "Question 7", "Question 226", "Question 1", "Question 173", "Question 238", "Question 46", "Question 108", "Question 114", "Question 119", "Question 251", "Question 197", "Question 159", "Question 72", "Question 70", "Question 150", "Question 289", "Question 143", "Question 141", "Question 47", "Question 69", "Question 88", "Question 244", "Question 189", "Question 129", "Question 266", "Question 221", "Question 248", "Question 92", "Question 236", "Question 33", "Question 175", "Question 133", "Question 210", "Question 228", "Question 213", "Question 64", "Question 223", "Question 198", "Question 202", "Question 68", "Question 291", "Question 230", "Question 270", "Question 103", "Question 83", "Question 271", "Question 62", "Question 109", "Question 121", "Question 10", "Question 232"]