【发布时间】:2015-06-17 13:30:26
【问题描述】:
我想随机排列我的数组问题,并在程序启动时使用随机排列的数组。我创建了这个对数组进行洗牌的函数。
func shuffleQuestions() {
var shuffledQuestions = shuffle(questions)
}
这给了我一个包含问题的数组,该数组继承了下面结构中的值。我遇到的问题是它是 shuffleQuestions 函数本地的。如何创建一个空的 structs 变量数组,我可以在全局范围内声明它以将打乱的问题放入其中。我需要创建一个新课程吗?
func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let c = count(list)
for i in 0..<(c - 1) {
let j = Int(arc4random_uniform(UInt32(c - i))) + i
swap(&list[i], &list[j])
}
return list
}
我的结构数组
class QuizQuestion {
let question: String!
let answer: Bool!
let explanation: String!
var usersAnswer: Bool?
var answerSubmitted: Bool?
init(question: String, answer: Bool, explanation: String) {
self.question = question
self.answer = answer
self.explanation = explanation
}
}
var questions = [
QuizQuestion(question: "Do I like coffee?", answer: true, explanation: "Because it's awesome!"),
QuizQuestion(question: "Is bacon god's gift to mankind?", answer: true, explanation: "Because it's awesome!"),
QuizQuestion(question: "Should I take a nap right now?", answer: true, explanation: "You gotta review some code!"),
QuizQuestion(question: "Should I take a nap right now?", answer: true, explanation: "You gotta review some code!")
]
【问题讨论】:
-
"但这似乎不起作用。" 是什么意思?
var shuffledQuestions = shuffle(questions)确实 创建了一个包含随机问题的数组。但是该数组是函数的本地数组,因此不能在其他地方使用。这是你的问题吗? -
我已经更新了我的问题以更好地反映我的问题,但是是的,这似乎是我面临的问题!
标签: arrays function swift struct shuffle