Arrays 将更改的数组重置为其原始值
我有一个数组。我需要使用随机数生成器循环遍历所有数组元素,并且不希望重复 刚开始编码时,我即兴使用数组元素值,使用后将其设置为“” 再次选择数组元素时,我会检查新数组的数组元素值是否等于原始数组。如果没有,我输入一个新的随机索引号,然后重试Arrays 将更改的数组重置为其原始值,arrays,swift,xcode,swift3,Arrays,Swift,Xcode,Swift3,我有一个数组。我需要使用随机数生成器循环遍历所有数组元素,并且不希望重复 刚开始编码时,我即兴使用数组元素值,使用后将其设置为“” 再次选择数组元素时,我会检查新数组的数组元素值是否等于原始数组。如果没有,我输入一个新的随机索引号,然后重试 这可以通过以下两种方式工作,直到重新启动(startover()) 然而 ''当我设置remainingQuestions=allQuestions-时,它在重新启动后不起作用。Result=每次重新启动时文本的(“/blank)”值的数量都会增加 ''当
这可以通过以下两种方式工作,直到重新启动(startover()) 然而 ''当我设置remainingQuestions=allQuestions-时,它在重新启动后不起作用。Result=每次重新启动时文本的(“/blank)”值的数量都会增加 ''当我设置remainingQuestions=questionBank()-时,它总是起作用
但是为什么我会做一些不同的事情。您的示例中缺少很多代码,因此需要进行一些更改,但要点如下:
import UIKit
class Question {
let questionText : String
let answer : Bool
init(text: String, correctAnswer: Bool) {
questionText = text
answer = correctAnswer
}
}
//Model: File - QuestionBank --------------------------------------
class QuestionBank {
var list = [Question]()
init() {
list.append(Question(text: "", correctAnswer: false))
}
init(list: [Question]) {
self.list = list
}
func pop() -> Question? {
guard list.count > 0 else {
return nil
}
return list.removeFirst()
}
}
//Controller: File - ViewController -------------------------------
var remainingQuestions = QuestionBank()
var allQuestions = QuestionBank()
//Iteration snippet: ------------------------------------------
func answerPressed() {
nextQuestion()
}
func nextQuestion() {
guard let nextQuestion = remainingQuestions.pop() else {
print("no questions left")
startOver()
return
}
questionLabel.text = nextQuestion.questionText
}
func startOver() {//also call on first setup
remainingQuestions = QuestionBank(list: allQuestions.list.shuffled())
nextQuestion()
}
给你一个洗牌数组的实际例子 在任何视图控制器中的
viewDidLoad()
中添加此项:
let questions:[String] = [
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"
]
for _ in 1...4 {
let shuffledQuestions:[String] = questions.shuffled()
print(shuffledQuestions)
}
运行此命令时,您将在调试控制台中看到问题数组输出四次,每次都是随机顺序。它看起来像这样:
["Six", "Nine", "One", "Five", "Four", "Two", "Ten", "Three", "Eight", "Seven"]
["Two", "Nine", "Seven", "Four", "Six", "Five", "Eight", "One", "Three", "Ten"]
["Nine", "Ten", "Four", "Two", "One", "Five", "Eight", "Three", "Six", "Seven"]
["Six", "Three", "Seven", "One", "Five", "Two", "Eight", "Nine", "Four", "Ten"]
当然,每次运行它时,顺序都会有所不同
所以,这里有一个完整的10个问题的真/假测验的例子,问题顺序是随机的(随机的)。回答第10个问题后,您可以点击“重新启动测验”按钮,您将得到相同的10个问题,但顺序不同:
//Model: File - Question ------------------------------------------
class Question {
var questionText : String
let answer : Bool
init(text: String, correctAnswer: Bool) {
questionText = text
answer = correctAnswer
}
}
//Model: File - QuestionBank --------------------------------------
class QuestionBank {
var list: [Question] = [
Question(text: "One is an Even number?", correctAnswer: false),
Question(text: "Two is an Even number?", correctAnswer: true),
Question(text: "Three is an Even number?", correctAnswer: false),
Question(text: "Four is an Even number?", correctAnswer: true),
Question(text: "Five is an Even number?", correctAnswer: false),
Question(text: "Six is an Even number?", correctAnswer: true),
Question(text: "Seven is an Even number?", correctAnswer: false),
Question(text: "Eight is an Even number?", correctAnswer: true),
Question(text: "Nine is an Even number?", correctAnswer: false),
Question(text: "Ten is an Even number?", correctAnswer: true),
]
}
class RandomizeQuestionsViewController: UIViewController {
let questionHeaderLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let questionLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let answerLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let nextButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .blue
v.setTitle("Next Question", for: .normal)
return v
}()
let restartButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
v.setTitle("Restart Quiz", for: .normal)
return v
}()
let trueButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitleColor(.lightGray, for: .disabled)
v.setTitleColor(.blue, for: .normal)
v.layer.borderColor = UIColor.red.cgColor
v.setTitle("True", for: .normal)
return v
}()
let falseButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitleColor(.blue, for: .normal)
v.setTitleColor(.lightGray, for: .disabled)
v.layer.borderColor = UIColor.red.cgColor
v.setTitle("False", for: .normal)
return v
}()
var shuffledQuestions: [Question] = [Question]()
// arrays are zero-based
var currentQuestionIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// add UI elements
view.addSubview(questionHeaderLabel)
view.addSubview(questionLabel)
view.addSubview(trueButton)
view.addSubview(falseButton)
view.addSubview(answerLabel)
view.addSubview(nextButton)
view.addSubview(restartButton)
NSLayoutConstraint.activate([
questionHeaderLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
questionHeaderLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
questionHeaderLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
questionHeaderLabel.heightAnchor.constraint(equalToConstant: 30.0),
questionLabel.topAnchor.constraint(equalTo: questionHeaderLabel.bottomAnchor, constant: 0.0),
questionLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
questionLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
questionLabel.heightAnchor.constraint(equalToConstant: 80.0),
trueButton.topAnchor.constraint(equalTo: questionLabel.bottomAnchor, constant: 40.0),
trueButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -60.0),
trueButton.widthAnchor.constraint(equalToConstant: 90.0),
falseButton.topAnchor.constraint(equalTo: questionLabel.bottomAnchor, constant: 40.0),
falseButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 60.0),
falseButton.widthAnchor.constraint(equalToConstant: 90.0),
answerLabel.topAnchor.constraint(equalTo: trueButton.bottomAnchor, constant: 40.0),
answerLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
answerLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
answerLabel.heightAnchor.constraint(equalToConstant: 80.0),
nextButton.topAnchor.constraint(equalTo: answerLabel.bottomAnchor, constant: 40.0),
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
nextButton.widthAnchor.constraint(equalToConstant: 160.0),
restartButton.topAnchor.constraint(equalTo: answerLabel.bottomAnchor, constant: 40.0),
restartButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
restartButton.widthAnchor.constraint(equalToConstant: 160.0),
])
trueButton.addTarget(self, action: #selector(trueTapped(_:)), for: .touchUpInside)
falseButton.addTarget(self, action: #selector(falseTapped(_:)), for: .touchUpInside)
nextButton.addTarget(self, action: #selector(nextQuestionTapped(_:)), for: .touchUpInside)
restartButton.addTarget(self, action: #selector(restartQuizTapped(_:)), for: .touchUpInside)
restartQuizTapped(nil)
}
@objc func restartQuizTapped(_ sender: Any?) -> Void {
// hide restart button
restartButton.isHidden = true
// nextQuestion func increments the index...
// set it to -1 so the first question will be index 0
currentQuestionIndex = -1
// shuffle the questions
shuffledQuestions = QuestionBank().list.shuffled()
// show the question
nextQuestionTapped(nil)
}
@objc func nextQuestionTapped(_ sender: Any?) -> Void {
// hide next button
nextButton.isHidden = true
// reset true/false button borders
trueButton.layer.borderWidth = 0
falseButton.layer.borderWidth = 0
// increment the index
currentQuestionIndex += 1
if currentQuestionIndex < shuffledQuestions.count {
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
// set the label texts
questionHeaderLabel.text = "Question \(currentQuestionIndex + 1) of \(shuffledQuestions.count)"
questionLabel.text = q.questionText
answerLabel.text = "Select True or False"
// enable true/false buttons
trueButton.isEnabled = true
falseButton.isEnabled = true
} else {
// out of questions, so show restart button
restartButton.isHidden = false
}
}
@objc func trueTapped(_ sender: Any?) -> Void {
// highlight selected button
trueButton.layer.borderWidth = 3
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
var answerText = ""
if q.answer == true {
answerText = "Correct!" + "\n" + "It IS an Even number!"
} else {
answerText = "Wrong!" + "\n" + "It is NOT an Even number!"
}
updateUI(feedback: answerText)
}
@objc func falseTapped(_ sender: Any?) -> Void {
// highlight selected button
falseButton.layer.borderWidth = 3
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
var answerText = ""
if q.answer == false {
answerText = "Correct!" + "\n" + "It is NOT an Even number!"
} else {
answerText = "Wrong!" + "\n" + "It IS an Even number!"
}
updateUI(feedback: answerText)
}
func updateUI(feedback answer: String) -> Void {
answerLabel.text = answer
// disable true/false buttons
trueButton.isEnabled = false
falseButton.isEnabled = false
// if there are more questions
if currentQuestionIndex < shuffledQuestions.count - 1 {
// show next question button
nextButton.isHidden = false
} else {
// show restart button
restartButton.isHidden = false
}
}
}
//模型:文件-问题------------------------------------------
课堂提问{
变量文本:字符串
让我们回答:布尔
初始化(文本:字符串,正确答案:Bool){
问题文本=文本
答案=正确答案
}
}
//模型:文件库--------------------------------------
班级问题库{
变量列表:[问题]=[
问题(正文:“一是偶数?”,正确答案:假),
问题(文本:“2是偶数?”,正确答案:真),
问题(正文:“三是偶数?”,正确答案:错),
问题(正文:“四是偶数?”,正确答案:正确),
问题(文本:“五是偶数?”,正确答案:错),
问题(正文:“六是偶数?”,正确答案:正确),
问题(文本:“七是偶数?”,正确答案:错),
问题(正文:“八是偶数?”,正确答案:正确),
问题(文本:“九是偶数?”,正确答案:错),
问题(文本:“十是偶数?”,正确答案:正确),
]
}
类RandomizeQuestionViewController:UIViewController{
let questionHeaderLabel:UILabel={
设v=UILabel()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 背景色=.cyan
v、 numberOfLines=0
v、 textAlignment=.center
返回v
}()
let questionLabel:UILabel={
设v=UILabel()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 背景颜色=.黄色
v、 numberOfLines=0
v、 textAlignment=.center
返回v
}()
让应答器标签:UILabel={
设v=UILabel()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 背景颜色=.黄色
v、 numberOfLines=0
v、 textAlignment=.center
返回v
}()
let nextButton:ui按钮={
设v=UIButton()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 背景颜色=.blue
v、 setTitle(“下一个问题”,用于:。正常)
返回v
}()
让重新启动按钮:UIButton={
设v=UIButton()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 背景颜色=.red
v、 setTitle(“重启测验”,用于:。正常)
返回v
}()
让trueButton:UIButton={
设v=UIButton()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 backgroundColor=UIColor(白色:0.9,alpha:1.0)
v、 setTitleColor(.lightGray,用于:。已禁用)
v、 setTitleColor(.blue,表示:。正常)
v、 layer.borderColor=UIColor.red.cgColor
v、 setTitle(“True”,表示:。正常)
返回v
}()
let falseButton:UIButton={
设v=UIButton()
v、 translatesAutoresizingMaskIntoConstraints=false
v、 backgroundColor=UIColor(白色:0.9,alpha:1.0)
v、 setTitleColor(.blue,表示:。正常)
v、 setTitleColor(.lightGray,用于:。已禁用)
v、 layer.borderColor=UIColor.red.cgColor
v、 setTitle(“False”,用于:。正常)
返回v
}()
var shuffledQuestions:[问题]=[问题]()
//数组是零基的
var currentQuestionIndex:Int=0
重写func viewDidLoad(){
super.viewDidLoad()
//添加UI元素
view.addSubview(问题标题标签)
view.addSubview(问题标签)
view.addSubview(trueButton)
view.addSubview(错误按钮)
view.addSubview(应答标签)
view.addSubview(下一个按钮)
view.addSubview(重新启动按钮)
NSLayoutConstraint.activate([
questionHeaderLabel.topAnchor.constraint(等式:view.safeAreaLayoutGuide.topAnchor,常量:40.0),
问题标题标记.引导锚定约束(等于:view.SafeArealLayoutGuide.leadingAnchor,常量:40.0),
questionHeaderLabel.trailingAnchor.constraint(等式:view.safeArea LayoutGuide.trailingAnchor,常数:-40.0),
questionHeaderLabel.heightAnchor.constraint(等式常量:30.0),
questionLabel.topAnchor.constraint(等式:questionHeaderLabel.bottomAnchor,常量:0.0),
问题标签.leadingAnchor.constraint(等式:view.SafeArealLayoutGuide.leadingAnchor,Constant
//Model: File - Question ------------------------------------------
class Question {
var questionText : String
let answer : Bool
init(text: String, correctAnswer: Bool) {
questionText = text
answer = correctAnswer
}
}
//Model: File - QuestionBank --------------------------------------
class QuestionBank {
var list: [Question] = [
Question(text: "One is an Even number?", correctAnswer: false),
Question(text: "Two is an Even number?", correctAnswer: true),
Question(text: "Three is an Even number?", correctAnswer: false),
Question(text: "Four is an Even number?", correctAnswer: true),
Question(text: "Five is an Even number?", correctAnswer: false),
Question(text: "Six is an Even number?", correctAnswer: true),
Question(text: "Seven is an Even number?", correctAnswer: false),
Question(text: "Eight is an Even number?", correctAnswer: true),
Question(text: "Nine is an Even number?", correctAnswer: false),
Question(text: "Ten is an Even number?", correctAnswer: true),
]
}
class RandomizeQuestionsViewController: UIViewController {
let questionHeaderLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let questionLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let answerLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.numberOfLines = 0
v.textAlignment = .center
return v
}()
let nextButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .blue
v.setTitle("Next Question", for: .normal)
return v
}()
let restartButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
v.setTitle("Restart Quiz", for: .normal)
return v
}()
let trueButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitleColor(.lightGray, for: .disabled)
v.setTitleColor(.blue, for: .normal)
v.layer.borderColor = UIColor.red.cgColor
v.setTitle("True", for: .normal)
return v
}()
let falseButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
v.setTitleColor(.blue, for: .normal)
v.setTitleColor(.lightGray, for: .disabled)
v.layer.borderColor = UIColor.red.cgColor
v.setTitle("False", for: .normal)
return v
}()
var shuffledQuestions: [Question] = [Question]()
// arrays are zero-based
var currentQuestionIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// add UI elements
view.addSubview(questionHeaderLabel)
view.addSubview(questionLabel)
view.addSubview(trueButton)
view.addSubview(falseButton)
view.addSubview(answerLabel)
view.addSubview(nextButton)
view.addSubview(restartButton)
NSLayoutConstraint.activate([
questionHeaderLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
questionHeaderLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
questionHeaderLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
questionHeaderLabel.heightAnchor.constraint(equalToConstant: 30.0),
questionLabel.topAnchor.constraint(equalTo: questionHeaderLabel.bottomAnchor, constant: 0.0),
questionLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
questionLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
questionLabel.heightAnchor.constraint(equalToConstant: 80.0),
trueButton.topAnchor.constraint(equalTo: questionLabel.bottomAnchor, constant: 40.0),
trueButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -60.0),
trueButton.widthAnchor.constraint(equalToConstant: 90.0),
falseButton.topAnchor.constraint(equalTo: questionLabel.bottomAnchor, constant: 40.0),
falseButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 60.0),
falseButton.widthAnchor.constraint(equalToConstant: 90.0),
answerLabel.topAnchor.constraint(equalTo: trueButton.bottomAnchor, constant: 40.0),
answerLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
answerLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
answerLabel.heightAnchor.constraint(equalToConstant: 80.0),
nextButton.topAnchor.constraint(equalTo: answerLabel.bottomAnchor, constant: 40.0),
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
nextButton.widthAnchor.constraint(equalToConstant: 160.0),
restartButton.topAnchor.constraint(equalTo: answerLabel.bottomAnchor, constant: 40.0),
restartButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
restartButton.widthAnchor.constraint(equalToConstant: 160.0),
])
trueButton.addTarget(self, action: #selector(trueTapped(_:)), for: .touchUpInside)
falseButton.addTarget(self, action: #selector(falseTapped(_:)), for: .touchUpInside)
nextButton.addTarget(self, action: #selector(nextQuestionTapped(_:)), for: .touchUpInside)
restartButton.addTarget(self, action: #selector(restartQuizTapped(_:)), for: .touchUpInside)
restartQuizTapped(nil)
}
@objc func restartQuizTapped(_ sender: Any?) -> Void {
// hide restart button
restartButton.isHidden = true
// nextQuestion func increments the index...
// set it to -1 so the first question will be index 0
currentQuestionIndex = -1
// shuffle the questions
shuffledQuestions = QuestionBank().list.shuffled()
// show the question
nextQuestionTapped(nil)
}
@objc func nextQuestionTapped(_ sender: Any?) -> Void {
// hide next button
nextButton.isHidden = true
// reset true/false button borders
trueButton.layer.borderWidth = 0
falseButton.layer.borderWidth = 0
// increment the index
currentQuestionIndex += 1
if currentQuestionIndex < shuffledQuestions.count {
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
// set the label texts
questionHeaderLabel.text = "Question \(currentQuestionIndex + 1) of \(shuffledQuestions.count)"
questionLabel.text = q.questionText
answerLabel.text = "Select True or False"
// enable true/false buttons
trueButton.isEnabled = true
falseButton.isEnabled = true
} else {
// out of questions, so show restart button
restartButton.isHidden = false
}
}
@objc func trueTapped(_ sender: Any?) -> Void {
// highlight selected button
trueButton.layer.borderWidth = 3
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
var answerText = ""
if q.answer == true {
answerText = "Correct!" + "\n" + "It IS an Even number!"
} else {
answerText = "Wrong!" + "\n" + "It is NOT an Even number!"
}
updateUI(feedback: answerText)
}
@objc func falseTapped(_ sender: Any?) -> Void {
// highlight selected button
falseButton.layer.borderWidth = 3
// get current Question object from shuffled array
let q: Question = shuffledQuestions[currentQuestionIndex]
var answerText = ""
if q.answer == false {
answerText = "Correct!" + "\n" + "It is NOT an Even number!"
} else {
answerText = "Wrong!" + "\n" + "It IS an Even number!"
}
updateUI(feedback: answerText)
}
func updateUI(feedback answer: String) -> Void {
answerLabel.text = answer
// disable true/false buttons
trueButton.isEnabled = false
falseButton.isEnabled = false
// if there are more questions
if currentQuestionIndex < shuffledQuestions.count - 1 {
// show next question button
nextButton.isHidden = false
} else {
// show restart button
restartButton.isHidden = false
}
}
}