Creating the Model Layer

View objects make up the UI, so developers typically create, configure, and connect view objects using Interface Builder. The parts of the model layer, on the other hand, are typically set up in code.

In the project navigator, select ViewController.swift. Add the following code that declares two arrays of strings and an integer.

class ViewController: UIViewController {
    @IBOutlet var questionLabel: UILabel!
    @IBOutlet var answerLabel: UILabel!

    let questions: [String] = [
        "What is 7+7?",
        "What is the capital of Vermont?",
        "What is cognac made from?"
    ]
    let answers: [String] = [
        "14",
        "Montpelier",
        "Grapes"
    ]
    var currentQuestionIndex: Int = 0
    ...
}

The arrays are ordered lists containing questions and answers. The integer will keep track of what question the user is on.

Notice that the arrays are declared using the let keyword, whereas the integer is declared using the var keyword. A constant is denoted with the let keyword; its value cannot change. The questions and answers arrays are constants. The questions and answers in this quiz will not change and, in fact, cannot be changed from their initial values.

A variable, on the other hand, is denoted by the var keyword; its value is allowed to change. You made the currentQuestionIndex property a variable because its value must be able to change as the user cycles through the questions and answers.

Implementing action methods

Now that you have questions and answers, you can finish implementing the action methods. In ViewController.swift, update showNextQuestion(_:) and showAnswer(_:).

...
@IBAction func showNextQuestion(_ sender: UIButton) {
    currentQuestionIndex += 1
    if currentQuestionIndex == questions.count {
        currentQuestionIndex = 0
    }

    let question: String = questions[currentQuestionIndex]
    questionLabel.text = question
    answerLabel.text = "???"
}

@IBAction func showAnswer(_ sender: UIButton) {
    let answer: String = answers[currentQuestionIndex]
    answerLabel.text = answer
}
...

Loading the first question

Just after the application is launched, you will want to load the first question from the array and use it to replace the ??? placeholder in the questionLabel label. A good way to do this is by overriding the viewDidLoad() method of ViewController. (Override means that you are providing a custom implementation for a method.) Add the method to ViewController.swift.

class ViewController: UIViewController {
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        questionLabel.text = questions[currentQuestionIndex]
    }
}

All the code for your application is now complete!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.70.203