Book Image

Swift Cookbook

Book Image

Swift Cookbook

Overview of this book

Table of Contents (18 chapters)
Swift Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Checking the right answer


This recipe will complete the previous one by checking the user's answer. If for any reason the answer receives a value out of range, this will be set to nil. Of course, in this application, it's not possible to answer with a wrong value, but remember that a good developer is always thinking about the possible software evolution.

Getting ready

Copy the previous recipe; if you like, you can rename the product name to Chapter 2 Examination 2 by simply renaming the target name, as shown here:

How to do it...

Follow these steps in order to check the answers:

  1. Go to the question.swift file. Now, replace the current class with the following one:

    struct Question {
        var question:String
        var answer1:String
        var answer2:String
        var answer3:String
        var rightAnswer:Int
        var userAnswer:Int? {
            willSet(newAnswer){
                if newAnswer? < 2 || newAnswer? > 3 {
                    userAnswer = nil
                     println("Wrong value, fixing it")
         ...