arrays - 如何访问这个结构数组 - Swift

标签 arrays swift struct instance

我创建了一个名为“questions”的数组,其中充满了结构“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)")

关于arrays - 如何访问这个结构数组 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666021/

相关文章:

java - 从字符串数组中删除一个字符

swift - 为什么 Swift 3 无法识别我的按钮点击?

ios - 使用 NSPredicate 在自定义对象的 NSArray 中搜索字符串

c - 如何在 C 中将行从矩阵传递到新数组

java - 将 DateTime 从 ISO_INSTANT 转换为从午夜算起的秒数

java - Android XML dataHandler getResources() 未定义

C语言中在最后位置插入节点的代码

uiwebview - 简单的 Swift WebView 不工作(Xcode 6 Beta 3)

c - 使用结构获取学生的姓名和分数

c - 我应该编写一个程序来对结构数组进行排序,但我不知道这样做