我怎样才能做一个 swift 多题测验,这样问题就不会重复了?
How can I make a swift multiple questions quiz so the questions do not repeat themselves?
我没有任何编程经验。几个月来,我一直在看 youtube 视频。如果有人可以帮助我,我将非常感激。当我 运行 使用模拟器的代码时,它会在出现下一个新问题之前多次重复问题。我希望它 运行 这样它只提出一个问题而不是一遍又一遍地重复同一个问题。请在下面找到代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var QuestionLabel: UILabel!
@IBOutlet weak var Button1: UIButton!
@IBOutlet weak var Button2: UIButton!
@IBOutlet weak var Button3: UIButton!
@IBOutlet weak var Button4: UIButton!
@IBOutlet weak var Next: UIButton!
@IBOutlet weak var LabelEnd: UILabel!
var CorrectAnswer = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
RamdomQuestions()
}
func RamdomQuestions () {
var RandomNumber = arc4random() % 4
RandomNumber += 1
switch (RandomNumber) {
case 1:
QuestionLabel.text = "Hola familia, Cual es mi nombre? "
Button1.setTitle ("Cesar", forState: UIControlState.Normal)
Button2.setTitle ("Karlos", forState: UIControlState.Normal)
Button3.setTitle ("William", forState: UIControlState.Normal)
Button4.setTitle ("Chiqui", forState: UIControlState.Normal)
CorrectAnswer = "2"
break
case 2:
QuestionLabel.text = "Hola famili, cual es mi apellido? "
Button1.setTitle ("Perez", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Sanchez", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 3:
QuestionLabel.text = "Quien hace la lachona mas rica? "
Button1.setTitle ("Willy", forState: UIControlState.Normal)
Button2.setTitle ("Mario", forState: UIControlState.Normal)
Button3.setTitle ("Karlos", forState: UIControlState.Normal)
Button4.setTitle ("Juan David", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 4:
QuestionLabel.text = "Quien hace las tartas mas lindas"
Button1.setTitle ("Jili", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Leidy y Liz", forState: UIControlState.Normal)
CorrectAnswer = "4"
break
default:
break
}
}
func Hide (){
LabelEnd.hidden = true
Next.hidden = true
}
func UnHide () {
LabelEnd.hidden = false
Next.hidden = false
}
@IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "1") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button2Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "2") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button3Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "3") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button4Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "4") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
@IBAction func Next(sender: AnyObject) {
RamdomQuestions()
}
}
试试下面的代码,希望它对你有用
class ViewController: UIViewController {
@IBOutlet weak var QuestionLabel: UILabel!
@IBOutlet weak var Button1: UIButton!
@IBOutlet weak var Button2: UIButton!
@IBOutlet weak var Button3: UIButton!
@IBOutlet weak var Button4: UIButton!
@IBOutlet weak var Next: UIButton!
@IBOutlet weak var LabelEnd: UILabel!
var CorrectAnswer = String()
var randomQuestionArray:[Int] = [1, 2, 3, 4]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
RamdomQuestions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func RamdomQuestions () {
let randomIndex = Int(arc4random_uniform(UInt32(randomQuestionArray.count)))
if randomQuestionArray.count > 0 {
switch (randomQuestionArray[randomIndex]) {
case 1:
QuestionLabel.text = "Hola familia, Cual es mi nombre? "
Button1.setTitle ("Cesar", forState: UIControlState.Normal)
Button2.setTitle ("Karlos", forState: UIControlState.Normal)
Button3.setTitle ("William", forState: UIControlState.Normal)
Button4.setTitle ("Chiqui", forState: UIControlState.Normal)
CorrectAnswer = "2"
break
case 2:
QuestionLabel.text = "Hola famili, cual es mi apellido? "
Button1.setTitle ("Perez", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Sanchez", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 3:
QuestionLabel.text = "Quien hace la lachona mas rica? "
Button1.setTitle ("Willy", forState: UIControlState.Normal)
Button2.setTitle ("Mario", forState: UIControlState.Normal)
Button3.setTitle ("Karlos", forState: UIControlState.Normal)
Button4.setTitle ("Juan David", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 4:
QuestionLabel.text = "Quien hace las tartas mas lindas"
Button1.setTitle ("Jili", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Leidy y Liz", forState: UIControlState.Normal)
CorrectAnswer = "4"
break
default:
break
}
randomQuestionArray.removeAtIndex(randomIndex)
}
}
func Hide () {
LabelEnd.hidden = true
Next.hidden = true
}
func UnHide () {
LabelEnd.hidden = false
Next.hidden = false
}
@IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "1") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button2Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "2") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button3Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "3") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button4Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "4") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
@IBAction func Next(sender: AnyObject) {
RamdomQuestions()
}
}
这个问题的典型解决方案是有一个问题数组(或模型中的索引),然后随机排列这个数组,使其随机。然后您可以遍历这些随机排列的问题,它们将以随机方式出现,但您不必担心它们会再次出现。
在 Swift 4.2 中,您将使用内置的 shuffle
或 shuffled
方法来打乱数组。
4.2之前的Swift版本,需要自己对数组进行shuffle。请注意,生成随机数时,不应将 arc4random
与 %
运算符一起使用。这就引入了 modulo bias. Instead, use arc4random_uniform
which generates uniformly distributed random numbers within a range of values. And shuffling the array, you should use a Fisher-Yates algorithm, which eliminates some subtle biases introduced by naive shuffling algorithms. For general information, see the Fisher-Yates article in Wikipedia. For specific Swift implementation, see How do I shuffle an array in Swift?。无论如何,算法看起来像:
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
if count < 2 { return } // empty and single-element collections don't shuffle
for i in 0 ..< count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i)))
if j != 0 {
let current = index(startIndex, offsetBy: i)
let swapped = index(current, offsetBy: j)
swapAt(current, swapped)
}
}
}
/// Return shuffled collection the elements of `self`.
func shuffled() -> Self {
var results = self
results.shuffle()
return results
}
}
然后您可以像这样使用它:
var questionIndexes = Array(0 ..< questions.count) // builds an array [0, 1, 2, ... n-1], where _n_ is the number of questions
questionIndexes.shuffle() // shuffle that list
你最终得到一个数字 0 到 n-1 的数组,这些数字被打乱(即以随机顺序出现,但没有数字出现超过一次)。您现在可以遍历这个 questionIndexes
数组,每个问题将被问一次且仅一次,但它们将以随机顺序呈现。
一些不相关的观察结果:
您可能希望采用 Cocoa 命名约定,即该方法和 属性 名称应始终以小写字母开头。只有数据类型(例如 类 或结构)和枚举以大写字母开头。
在Swift中执行switch
语句时,不需要break
。 Swift 不会像 Objective-C 那样失败。当我解决下面的第 5 点时,结果我最终完全分解了 switch
语句,但为了您将来的参考,您不需要在每个 [= 的末尾 break
25=] 在 Swift 中就像你在基于 C 的编程语言中所做的那样 Objective-C。事实上,如果您希望 Swift case
语句进入下一个语句,就像在 Objective-C 中那样,您必须使用 fallthrough
关键字。
您可能不应该将 correctAnswer
初始化为 String()
。只需将其声明为可选(如果需要,可以隐式解包)。
更好的是,correctAnswer
应该是 Int
而不是 String
。我还会使用从零开始的值,以便我可以轻松地查找该值以确认是否按下了正确的按钮。
这是一个更高级的主题,但我建议将 "model"(即关于问题文本、潜在答案和正确答案的数据)与 "controller" 分开(从模型中获取信息并更新视图的代码)。这是我们在应用程序中使用的 model-view-controller 范例的一部分。它使您的应用程序在未来更易于维护(例如,您可以添加更多问题、更改问题等,但不必接触视图控制器中的代码)。它还支持更灵活的模式(例如,问题和答案可以由远程 Web 服务提供或存储在数据库中)。
例如,您可能有一个类型可以捕获问题及其可能的答案,并确定哪个是正确答案。
struct Question {
let question: String
let answers: [String]
let correctAnswer: Int
}
您的模型可能包含 Question
个对象的数组:
var questions: [Question] = [
Question(
question: "Hola familia, Cual es mi nombre?",
answers: ["Cesar", "Karlos", "William", "Chiqui"],
correctAnswer: 1),
Question(
question: "Hola famili, cual es mi apellido?",
answers: ["Perez", "Carvajal", "Garcia", "Sanchez"],
correctAnswer: 0),
Question(
question: "Quien hace la lachona mas rica?",
answers: ["Willy", "Mario", "Karlos", "Juan David"],
correctAnswer: 2),
Question(
question: "Quien hace las tartas mas lindas?",
answers: ["Jili", "Carvajal", "Garcia", "Leidy y Liz"],
correctAnswer: 3)
]
请注意,请原谅我将这些问题中的 "correct answer" 更改为您问题中的内容。我只是想说明我们正在处理从 0
到 3
的数字(不是 1
到 4
)。
将所有这些放在一起,您的实现可能如下所示:
import UIKit
struct Question {
let question: String
let answers: [String]
let correctAnswer: Int
}
class ViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
lazy var buttons: [UIButton] = { return [self.button1, self.button2, self.button3, self.button4] }()
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var endLabel: UILabel!
var questions: [Question] = [
Question(
question: "Hola familia, Cual es mi nombre?",
answers: ["Cesar", "Karlos", "William", "Chiqui"],
correctAnswer: 1),
Question(
question: "Hola famili, cual es mi apellido?",
answers: ["Perez", "Carvajal", "Garcia", "Sanchez"],
correctAnswer: 0),
Question(
question: "Quien hace la lachona mas rica?",
answers: ["Willy", "Mario", "Karlos", "Juan David"],
correctAnswer: 2),
Question(
question: "Quien hace las tartas mas lindas?",
answers: ["Jili", "Carvajal", "Garcia", "Leidy y Liz"],
correctAnswer: 3)
]
var questionIndexes: [Int]!
var currentQuestionIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
questionIndexes = Array(0 ..< questions.count) // builds an array [0, 1, 2, ... n]
questionIndexes.shuffle() // randomizes that list
updateLabelsAndButtonsForIndex(0)
}
func updateLabelsAndButtonsForIndex(questionIndex: Int) {
// if we're done, show message in `endLabel` and hide `nextButton`
guard questionIndex < questions.count else {
endLabel.hidden = false
endLabel.text = "All done!"
nextButton.hidden = true
return
}
// update our property
currentQuestionIndex = questionIndex
// hide end label and next button
hideEndLabelAndNextButton()
// identify which question we're presenting
let questionObject = questions[questionIndexes[questionIndex]]
// update question label and answer buttons accordingly
questionLabel.text = questionObject.question
for (answerIndex, button) in buttons.enumerate() {
button.setTitle(questionObject.answers[answerIndex], forState: .Normal)
}
}
func hideEndLabelAndNextButton() {
endLabel.hidden = true
nextButton.hidden = true
}
func unhideEndLabelAndNextButton() {
endLabel.hidden = false
nextButton.hidden = false
}
// note, because I created that array of `buttons`, I now don't need
// to have four `@IBAction` methods, one for each answer button, but
// rather I can look up the index for the button in my `buttons` array
// and see if the index for the button matches the index of the correct
// answer.
@IBAction func didTapAnswerButton(button: UIButton) {
unhideEndLabelAndNextButton()
let buttonIndex = buttons.indexOf(button)
let questionObject = questions[questionIndexes[currentQuestionIndex]]
if buttonIndex == questionObject.correctAnswer {
endLabel.text = "Correcto"
} else {
endLabel.text = "Falso"
}
}
@IBAction func didTapNextButton(sender: AnyObject) {
updateLabelsAndButtonsForIndex(currentQuestionIndex + 1)
}
}
里面隐藏了很多东西,所以如果您不完全了解这里发生的一切,我不会担心细节。但关键是,在你的模型中建立一个索引数组,打乱它,然后你可以继续遍历这个打乱的数组,你保证你不会问同样的问题两次。
我最初连接了
@IBAction func didTapAnswerButton(button:
和
@IBAction func didTapNextButton(sender:
五个按钮,模拟器没有在屏幕上显示正确或错误。
我又试了一次,刚连接
@IBAction func didTapAnswerButton(button:
五个按钮和
@IBAction func didTapNextButton(sender:
单击“下一步”按钮,它起作用了。
我没有任何编程经验。几个月来,我一直在看 youtube 视频。如果有人可以帮助我,我将非常感激。当我 运行 使用模拟器的代码时,它会在出现下一个新问题之前多次重复问题。我希望它 运行 这样它只提出一个问题而不是一遍又一遍地重复同一个问题。请在下面找到代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var QuestionLabel: UILabel!
@IBOutlet weak var Button1: UIButton!
@IBOutlet weak var Button2: UIButton!
@IBOutlet weak var Button3: UIButton!
@IBOutlet weak var Button4: UIButton!
@IBOutlet weak var Next: UIButton!
@IBOutlet weak var LabelEnd: UILabel!
var CorrectAnswer = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
RamdomQuestions()
}
func RamdomQuestions () {
var RandomNumber = arc4random() % 4
RandomNumber += 1
switch (RandomNumber) {
case 1:
QuestionLabel.text = "Hola familia, Cual es mi nombre? "
Button1.setTitle ("Cesar", forState: UIControlState.Normal)
Button2.setTitle ("Karlos", forState: UIControlState.Normal)
Button3.setTitle ("William", forState: UIControlState.Normal)
Button4.setTitle ("Chiqui", forState: UIControlState.Normal)
CorrectAnswer = "2"
break
case 2:
QuestionLabel.text = "Hola famili, cual es mi apellido? "
Button1.setTitle ("Perez", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Sanchez", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 3:
QuestionLabel.text = "Quien hace la lachona mas rica? "
Button1.setTitle ("Willy", forState: UIControlState.Normal)
Button2.setTitle ("Mario", forState: UIControlState.Normal)
Button3.setTitle ("Karlos", forState: UIControlState.Normal)
Button4.setTitle ("Juan David", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 4:
QuestionLabel.text = "Quien hace las tartas mas lindas"
Button1.setTitle ("Jili", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Leidy y Liz", forState: UIControlState.Normal)
CorrectAnswer = "4"
break
default:
break
}
}
func Hide (){
LabelEnd.hidden = true
Next.hidden = true
}
func UnHide () {
LabelEnd.hidden = false
Next.hidden = false
}
@IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "1") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button2Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "2") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button3Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "3") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
func Button4Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "4") {
LabelEnd.text = "Correcto"
}
else{
LabelEnd.text = "Falso"
}
}
@IBAction func Next(sender: AnyObject) {
RamdomQuestions()
}
}
试试下面的代码,希望它对你有用
class ViewController: UIViewController {
@IBOutlet weak var QuestionLabel: UILabel!
@IBOutlet weak var Button1: UIButton!
@IBOutlet weak var Button2: UIButton!
@IBOutlet weak var Button3: UIButton!
@IBOutlet weak var Button4: UIButton!
@IBOutlet weak var Next: UIButton!
@IBOutlet weak var LabelEnd: UILabel!
var CorrectAnswer = String()
var randomQuestionArray:[Int] = [1, 2, 3, 4]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
RamdomQuestions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func RamdomQuestions () {
let randomIndex = Int(arc4random_uniform(UInt32(randomQuestionArray.count)))
if randomQuestionArray.count > 0 {
switch (randomQuestionArray[randomIndex]) {
case 1:
QuestionLabel.text = "Hola familia, Cual es mi nombre? "
Button1.setTitle ("Cesar", forState: UIControlState.Normal)
Button2.setTitle ("Karlos", forState: UIControlState.Normal)
Button3.setTitle ("William", forState: UIControlState.Normal)
Button4.setTitle ("Chiqui", forState: UIControlState.Normal)
CorrectAnswer = "2"
break
case 2:
QuestionLabel.text = "Hola famili, cual es mi apellido? "
Button1.setTitle ("Perez", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Sanchez", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 3:
QuestionLabel.text = "Quien hace la lachona mas rica? "
Button1.setTitle ("Willy", forState: UIControlState.Normal)
Button2.setTitle ("Mario", forState: UIControlState.Normal)
Button3.setTitle ("Karlos", forState: UIControlState.Normal)
Button4.setTitle ("Juan David", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 4:
QuestionLabel.text = "Quien hace las tartas mas lindas"
Button1.setTitle ("Jili", forState: UIControlState.Normal)
Button2.setTitle ("Carvajal", forState: UIControlState.Normal)
Button3.setTitle ("Garcia", forState: UIControlState.Normal)
Button4.setTitle ("Leidy y Liz", forState: UIControlState.Normal)
CorrectAnswer = "4"
break
default:
break
}
randomQuestionArray.removeAtIndex(randomIndex)
}
}
func Hide () {
LabelEnd.hidden = true
Next.hidden = true
}
func UnHide () {
LabelEnd.hidden = false
Next.hidden = false
}
@IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "1") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button2Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "2") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button3Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "3") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
func Button4Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "4") {
LabelEnd.text = "Correcto"
} else{
LabelEnd.text = "Falso"
}
}
@IBAction func Next(sender: AnyObject) {
RamdomQuestions()
}
}
这个问题的典型解决方案是有一个问题数组(或模型中的索引),然后随机排列这个数组,使其随机。然后您可以遍历这些随机排列的问题,它们将以随机方式出现,但您不必担心它们会再次出现。
在 Swift 4.2 中,您将使用内置的 shuffle
或 shuffled
方法来打乱数组。
4.2之前的Swift版本,需要自己对数组进行shuffle。请注意,生成随机数时,不应将 arc4random
与 %
运算符一起使用。这就引入了 modulo bias. Instead, use arc4random_uniform
which generates uniformly distributed random numbers within a range of values. And shuffling the array, you should use a Fisher-Yates algorithm, which eliminates some subtle biases introduced by naive shuffling algorithms. For general information, see the Fisher-Yates article in Wikipedia. For specific Swift implementation, see How do I shuffle an array in Swift?。无论如何,算法看起来像:
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
if count < 2 { return } // empty and single-element collections don't shuffle
for i in 0 ..< count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i)))
if j != 0 {
let current = index(startIndex, offsetBy: i)
let swapped = index(current, offsetBy: j)
swapAt(current, swapped)
}
}
}
/// Return shuffled collection the elements of `self`.
func shuffled() -> Self {
var results = self
results.shuffle()
return results
}
}
然后您可以像这样使用它:
var questionIndexes = Array(0 ..< questions.count) // builds an array [0, 1, 2, ... n-1], where _n_ is the number of questions
questionIndexes.shuffle() // shuffle that list
你最终得到一个数字 0 到 n-1 的数组,这些数字被打乱(即以随机顺序出现,但没有数字出现超过一次)。您现在可以遍历这个 questionIndexes
数组,每个问题将被问一次且仅一次,但它们将以随机顺序呈现。
一些不相关的观察结果:
您可能希望采用 Cocoa 命名约定,即该方法和 属性 名称应始终以小写字母开头。只有数据类型(例如 类 或结构)和枚举以大写字母开头。
在Swift中执行
switch
语句时,不需要break
。 Swift 不会像 Objective-C 那样失败。当我解决下面的第 5 点时,结果我最终完全分解了switch
语句,但为了您将来的参考,您不需要在每个 [= 的末尾break
25=] 在 Swift 中就像你在基于 C 的编程语言中所做的那样 Objective-C。事实上,如果您希望 Swiftcase
语句进入下一个语句,就像在 Objective-C 中那样,您必须使用fallthrough
关键字。您可能不应该将
correctAnswer
初始化为String()
。只需将其声明为可选(如果需要,可以隐式解包)。更好的是,
correctAnswer
应该是Int
而不是String
。我还会使用从零开始的值,以便我可以轻松地查找该值以确认是否按下了正确的按钮。这是一个更高级的主题,但我建议将 "model"(即关于问题文本、潜在答案和正确答案的数据)与 "controller" 分开(从模型中获取信息并更新视图的代码)。这是我们在应用程序中使用的 model-view-controller 范例的一部分。它使您的应用程序在未来更易于维护(例如,您可以添加更多问题、更改问题等,但不必接触视图控制器中的代码)。它还支持更灵活的模式(例如,问题和答案可以由远程 Web 服务提供或存储在数据库中)。
例如,您可能有一个类型可以捕获问题及其可能的答案,并确定哪个是正确答案。
struct Question { let question: String let answers: [String] let correctAnswer: Int }
您的模型可能包含
Question
个对象的数组:var questions: [Question] = [ Question( question: "Hola familia, Cual es mi nombre?", answers: ["Cesar", "Karlos", "William", "Chiqui"], correctAnswer: 1), Question( question: "Hola famili, cual es mi apellido?", answers: ["Perez", "Carvajal", "Garcia", "Sanchez"], correctAnswer: 0), Question( question: "Quien hace la lachona mas rica?", answers: ["Willy", "Mario", "Karlos", "Juan David"], correctAnswer: 2), Question( question: "Quien hace las tartas mas lindas?", answers: ["Jili", "Carvajal", "Garcia", "Leidy y Liz"], correctAnswer: 3) ]
请注意,请原谅我将这些问题中的 "correct answer" 更改为您问题中的内容。我只是想说明我们正在处理从
0
到3
的数字(不是1
到4
)。
将所有这些放在一起,您的实现可能如下所示:
import UIKit
struct Question {
let question: String
let answers: [String]
let correctAnswer: Int
}
class ViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
lazy var buttons: [UIButton] = { return [self.button1, self.button2, self.button3, self.button4] }()
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var endLabel: UILabel!
var questions: [Question] = [
Question(
question: "Hola familia, Cual es mi nombre?",
answers: ["Cesar", "Karlos", "William", "Chiqui"],
correctAnswer: 1),
Question(
question: "Hola famili, cual es mi apellido?",
answers: ["Perez", "Carvajal", "Garcia", "Sanchez"],
correctAnswer: 0),
Question(
question: "Quien hace la lachona mas rica?",
answers: ["Willy", "Mario", "Karlos", "Juan David"],
correctAnswer: 2),
Question(
question: "Quien hace las tartas mas lindas?",
answers: ["Jili", "Carvajal", "Garcia", "Leidy y Liz"],
correctAnswer: 3)
]
var questionIndexes: [Int]!
var currentQuestionIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
questionIndexes = Array(0 ..< questions.count) // builds an array [0, 1, 2, ... n]
questionIndexes.shuffle() // randomizes that list
updateLabelsAndButtonsForIndex(0)
}
func updateLabelsAndButtonsForIndex(questionIndex: Int) {
// if we're done, show message in `endLabel` and hide `nextButton`
guard questionIndex < questions.count else {
endLabel.hidden = false
endLabel.text = "All done!"
nextButton.hidden = true
return
}
// update our property
currentQuestionIndex = questionIndex
// hide end label and next button
hideEndLabelAndNextButton()
// identify which question we're presenting
let questionObject = questions[questionIndexes[questionIndex]]
// update question label and answer buttons accordingly
questionLabel.text = questionObject.question
for (answerIndex, button) in buttons.enumerate() {
button.setTitle(questionObject.answers[answerIndex], forState: .Normal)
}
}
func hideEndLabelAndNextButton() {
endLabel.hidden = true
nextButton.hidden = true
}
func unhideEndLabelAndNextButton() {
endLabel.hidden = false
nextButton.hidden = false
}
// note, because I created that array of `buttons`, I now don't need
// to have four `@IBAction` methods, one for each answer button, but
// rather I can look up the index for the button in my `buttons` array
// and see if the index for the button matches the index of the correct
// answer.
@IBAction func didTapAnswerButton(button: UIButton) {
unhideEndLabelAndNextButton()
let buttonIndex = buttons.indexOf(button)
let questionObject = questions[questionIndexes[currentQuestionIndex]]
if buttonIndex == questionObject.correctAnswer {
endLabel.text = "Correcto"
} else {
endLabel.text = "Falso"
}
}
@IBAction func didTapNextButton(sender: AnyObject) {
updateLabelsAndButtonsForIndex(currentQuestionIndex + 1)
}
}
里面隐藏了很多东西,所以如果您不完全了解这里发生的一切,我不会担心细节。但关键是,在你的模型中建立一个索引数组,打乱它,然后你可以继续遍历这个打乱的数组,你保证你不会问同样的问题两次。
我最初连接了
@IBAction func didTapAnswerButton(button:
和
@IBAction func didTapNextButton(sender:
五个按钮,模拟器没有在屏幕上显示正确或错误。
我又试了一次,刚连接
@IBAction func didTapAnswerButton(button:
五个按钮和
@IBAction func didTapNextButton(sender:
单击“下一步”按钮,它起作用了。