繁体   English   中英

如何访问此结构数组-Swift

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM