-1
我尝试使用下面的扩展洗牌我的阵列中的plist字典第20项:如何获得斯威夫特
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
}
}
我然后使用此代码重新洗牌,并让我的plist中第20个项目:
var questionsArray = [myPlistArray?.shuffled]
let shuffledQuestions = questionsArray.shuffle() // instance member cannot be used on type 'myViewController'
let first20 = questionsArray.prefix(20)
不过,我总是得到这个错误:// 实例成员不能在类型中使用“myViewController”
有谁知道怎么做我对吗? 还是有人知道我该如何洗牌pList项目并获得前20项?
我的问题是相当有这一个相同的:How to return first 5 objects of Array in Swift?,但是,我的数据是在的plist字典文件...
不管怎么说,我的plist文件是这样的:myPlistArray.plist
它仍然显示像这样:'let questionsArray = myPlistArray?.shuffled let first20 = questionsArray.prefix(20)//实例成员'questionsArray'不能用于'myViewController'类型 – pinkBlossoms7
我应该把代码放入'viewDidLoad中'?如果是,我怎么称呼它?谢谢你的帮助。 – pinkBlossoms7
你问“我应该把代码放在'viewDidLoad'吗?”对于您应该放置代码的位置没有普遍的答案。这取决于你需要它的地方,这取决于你想用它做什么。我不太了解你需要回答的问题。然后你问:“如果是,我怎么称呼它?”这个问题并没有意义。如果你把代码放在viewDidLoad中,它会在viewDidLoad被系统调用时运行。你根本就不打电话。你问你如何到达前20阵列? –