[英]How do I access this array of structs - Swift
我創建了一個名為“問題”的數組,該數組充滿了結構“ QuizQuestion”的實例-基本上,我希望“ nextQuestion”函數從結構(問題)數組中提取下一個問題並將其顯示給用戶(我了解如何通過標簽等顯示數據,我只是不知道如何訪問它)。
我嘗試過調用數組索引,然后再調用實例,但這似乎不起作用。 我也嘗試過創建“ QuizQuestion”的實例作為變量,並在“ NextQuestion”函數中使用它的實例,但是我不知道如何從“問題”中自動提取問題。
謝謝
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var explanationLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
questionVariable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
struct QuizQuestion {
let question: String
let answer: Bool
let explanation: String
}
let questions: [QuizQuestion] = [
QuizQuestion(question: "Red is a four letter word", answer: false, explanation: "Red is not a four letter word"),
QuizQuestion(question: "Dog is a three letter word", answer: true, explanation: "Dog is most likely a three letter word"),
QuizQuestion(question: "Cow is a three letter word", answer: true, explanation: "Cow is most likely a three letter word")
]
var nextQuestion = QuizQuestion.self[1]
func questionVariable() {
if nextQuestion.answer == true {
questionLabel.text = nextQuestion.question
explanationLabel.text = nextQuestion.explanation
answerLabel.text = "Correct"
}
}
}
您可以如下定義嵌套函數 (Swift中最簡單的閉包形式):
func getNextQuestion() -> (Int) -> QuizQuestion!
{
func incrementor(var index:Int) -> QuizQuestion! {
if index < questions.count && index >= 0 {
return questions[index]
}
else {
return nil
}
}
return incrementor
}
然后您可以訪問您的問題列表,如下所示
let nextQuestion = getNextQuestion()
var question_1 = nextQuestion(0)
var question_2 = nextQuestion(1)
var question_3 = nextQuestion(2)
println("1.question text: \(question_1.question)")
println("2.question text: \(question_2.question)")
println("3.question text: \(question_3.question)")
一個簡單的函數,用於從數組中檢索問題。 聲明一個實例變量以保存當前索引。
var currentIndex = 0
func nextQuestion() -> QuizQuestion {
// initialize current question
var currentQuestion: QuizQuestion = QuizQuestion(question: "", answer: false, explanation: "")
if currentIndex < questions.count {
currentQuestion = questions[currentIndex]
}
currentIndex++
return currentQuestion
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.