Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift By Example

You're reading from   Swift By Example

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher
ISBN-13 9781785284700
Length 284 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Arrow right icon
View More author details
Toc

A Guess the Number app in Swift

As mentioned in the introduction of this chapter, learning a language is just half of the difficulty in building an app; the other half is the framework. This means that learning a language is not enough. In this part of the chapter, we'll implement a simple Guess the Number app, just to become familiar with Xcode and part of the CocoaTouch framework.

The app is…

Our first complete Swift app is a Guess the Number app—a classic educational game for children where the player must guess a number generated randomly by the app.

For each guess, the app tells the player whether the guess is greater or lower than the generated number (also called the secret number).

Before diving into the code, we must define the interface of the app and the expected workflow.

This game presents only one screen, which is shown in the following screenshot:

The app is…

At the top of the screen, a label reports the name of the app—Guess a Number.

In the next row, another static label with the word between, connects the title with a dynamic label that reports the current range. The text inside the label must change every time a new number is inserted. A text field at the center of the screen is where the player will insert their guess.

A big button, with OK written on it, is the command that confirms that the player has inserted the chosen number.

The last two labels give feedback to the player:

  • Your last guess was too low is displayed if the number inserted is lower than the secret number
  • Your last guess was too high is displayed if it's greater than the secret number

The last label reports the current number of guesses. The workflow is straightforward:

  1. The app selects a random number.
  2. The player inserts their guess.
  3. If the number is equal to the secret number, a popup tells the player that they have won, and shows them the number of guesses.
  4. If the number is lower than the secret number but greater than the lower bound, it becomes the new lower bound. Otherwise, it is silently discarded.
  5. If the number is greater and lower than the upper bound, it becomes the new upper bound. Otherwise, it's, again, silently discarded.

Building a skeleton app

Let's start building the app - select a new project by going to File | New | Project…, as shown in this screenshot:

Building a skeleton app

The following screenshot shows Xcode asking for the type of app to be created. The app is really simple, so we choose Single View Application:

Building a skeleton app

Before starting to write code, we need to complete the configuration by adding the organization identifier, using the reverse domain name notation, and Product Name. Together, they produce a Bundle Identifier, the unique identifier of the app.

Pay attention to the selected language, which must obviously be Swift. Here is a screenshot that shows you how to fill in the form:

Building a skeleton app

Once done with this data, we are ready to run the app by going to Product | Run, as shown in this screenshot:

Building a skeleton app

After the simulator finishes loading the app, we can see our magnificent creation—a shiny, brilliant white page!

We can stop the app by going to Product | Stop, as shown in the following screenshot:

Building a skeleton app

Now we are ready to implement the app.

Adding the graphic components

When we are developing an iOS app, it is good practice to implement the app outside-in, starting from the graphics.

By taking a look at the files generated by the Xcode template, we can identify the two files that we'll use to implement Guess the Number:

  • Main.storyboard: This contains the graphics components
  • ViewController.swift: This handles all of the business logic of the app

Here is a screenshot that presents the structure of the files in an Xcode project:

Adding the graphic components

Let's start selecting the storyboard file to add the labels.

The first thing we notice is that the canvas is not the same size or ratio as an iPhone and an iPad. To handle different sizes and different devices, Apple (since iOS 5) added a constraints system, called AutoLayout, as a system to connect the graphics components in relative way, regardless of the actual size of the running device.

As Autolayout is beyond the scope of this chapter, we'll implement the created app only for iPhone 6.

After deciding our target device, we need to resize the canvas as per the real size of the device. From the tree structure at the right, we select ViewController, as shown here:

Adding the graphic components

After having done that, we move to the right-hand side, where there are the properties of the ViewController. There, we select the tab containing Simulated metrics, in which we can insert the requested size. The following screenshot will help you locate the correct tab:

Adding the graphic components

Now the size is the expected size, we can proceed to add labels, text fields, and the buttons from the list in the bottom-right corner of the screen.

To add a component, we must choose it from the list of components. Then, we must drag it onto the screen, where we can place it at the expected coordinates.

This screenshot shows the list of UI components, called an object library:

Adding the graphic components

When you add the text field, pay attention to selecting Number Pad as the value for Keyboard Type, as illustrated in the following screenshot:

Adding the graphic components

After selecting values for all the components, the app should appear as shown in the mockup we had drawn earlier, which this screenshot can confirm:

Adding the graphic components

Connecting the dots

If we run the app, the screen is the same as the one in the storyboard, but if we try to insert a number into the text field and then press the button, nothing happens.

This is because the storyboard is still detached from the ViewController, which handles all of the logic.

To connect the labels to the ViewController, we need to create instances of a label prepended with the @IBOutlet keyword. Using this signature, Interface Builder—the graphic editor inside Xcode—can recognize the instances available for connection to the components:

class ViewController: UIViewController {
    @IBOutlet weak var rangeLbl: UILabel!
    @IBOutlet weak var numberTxtField: UITextField!
    @IBOutlet weak var messageLbl: UILabel!
    @IBOutlet weak var numGuessesLbl: UILabel!

    @IBAction func onOkPressed(sender: AnyObject) {
    }
}

We have also added a method with the @IBAction prefix, which will be called when the button is pressed.

Now, let's move on to Interface Builder to connect the labels and outlets.

First of all, we need to select View Controller from the tree of components, as shown in this screenshot:

Connecting the dots

In the tabs to the right, select the outlet views, the last one with an arrow as a symbol. The following screenshot will help you find the correct symbol:

Connecting the dots

This shows all the possible outlets to which a component can be connected.

Upon moving the cursor onto the circle beside the rangeLbl label, we see that it changes to a cross. Now, we must click-and-drag a line to the label in the storyboard, as shown in this screenshot:

Connecting the dots

After doing the same for all the labels, the following screenshot shows the final configurations for the outlets:

Connecting the dots

For the action of the button, the process is similar: select the circle close to the onOkPressed action, and drag a line to the OK button, as shown in this screenshot:

Connecting the dots

When the button is released, a popup appears, with the list of possible events to connect the action to.

In our case, we connect the action to the Touch Up Inside event, which is triggered when we release the button without moving from its area. The following screenshot presents the list of the events raised by the UIButton component:

Connecting the dots

Now, suppose we added a log command like this one:

    @IBAction func onOkPressed(sender: AnyObject) {
        println(numberTxtField.text)
    }

Then, we can see the value of the text field we insert printed on the debug console.

Now that all the components are connected to their respective outlets, we can add the simple code required to create the app.

Adding the code

First of all, we need to add a few instance variables to handle the state:

    private var lowerBound = 0
    private var upperBound = 100
    private var numGuesses = 0
    private var secretNumber = 0

Just for the sake of clarity, and the separation of responsibilities, we create two extensions to the ViewController. An extension in Swift is similar to a category in Objective-C—a distinct data structure that adds a method to the class it extends.

Because we don't need the source of the class that the extension extends, we can use this mechanism to add features to third-party classes, or even to CocoaTouch classes.

Given this original purpose, extensions can also be used to organize the code inside a source file. This could seem a bit unorthodox, but if it doesn't hurt and is useful, why not use it?

The first extension contains the logic of the game:

private extension ViewController{
   enum Comparison{
        case Smaller
        case Greater
        case Equals
    }

   func selectedNumber(number: Int){
}
    
   func compareNumber(number: Int, otherNumber: Int) -> Comparison {
}
}

Note that the private keyword is added to the extension, making the methods inside private. This means that other classes that hold a reference to an instance of ViewController can't call these private methods.

Also, this piece of code shows that it is possible to create enumerations inside a private extension.

The second extension is for rendering all the labels:

private extension ViewController{
    func extractSecretNumber() {
    }
    
    func renderRange() {
    }
    
    func renderNumGuesses() {
}    
    func resetData() {
}    
    func resetMsg() {
}    
    func reset(){
        resetData()
        renderRange()
        renderNumGuesses()
        extractSecretNumber()
        resetMsg()
    }
}

Let's start from the beginning, which is the viewDidLoad method in the case of the ViewController:

    override func viewDidLoad() {
        super.viewDidLoad()
  numberTxtField.becomeFirstResponder()
        reset()
    }

When the becomeFirstResponder method is called, the component called—numberTxtField in our case—gets the focus, and the keyboard appears.

After that, reset() is called:

    func reset(){
        resetData()
        renderRange()
        renderNumGuesses()
        extractSecretNumber()
        resetMsg()
    }
This basically calls the reset method of each component:
    func resetData() {
        lowerBound = 0
        upperBound = 100
        numGuesses = 0
    }
    
    func resetMsg() {
        messageLbl.text = ""
    }

Then, the method is called and is used to render the two dynamic labels:

    func renderRange() {
        rangeLbl.text = "\(lowerBound) and \(upperBound)"
    }
    
    func renderNumGuesses() {
        numGuessesLbl.text = "Number of Guesses: \(numGuesses)"
    }

It also extracts the secret number using the arc4random_uniform function, and performs some typecast magic to align to the expected numeric type:

    func extractSecretNumber() {
        let diff = upperBound - lowerBound
        let randomNumber = Int(arc4random_uniform(UInt32(diff)))
        secretNumber = randomNumber + Int(lowerBound)
      }

Now, all the action is in the onOkPressed action (pun intended):

@IBAction func onOkPressed(sender: AnyObject) { 
    let number = numberTxtField.text.toInt()
  if let number = number {
      selectedNumber(number)
  } else {
   var alert = UIAlertController(title: nil, 
               message: "Enter a number", 
               preferredStyle: UIAlertControllerStyle.Alert)
   alert.addAction(UIAlertAction(title: "OK", 
               style: UIAlertActionStyle.Default, handler: nil))
   self.presentViewController(alert, 
                  animated: true, 
                  completion: nil)
        }
    }

Here, we retrieve the inserted number. Then, if it is valid (that is, it's not empty, not a word, and so on), we call the selectedNumber method. Otherwise, we present a popup asking for a number.

All the juice is in selectedNumber, where there is a switch case:

  func selectedNumber(number: Int){
        switch compareNumber(number, otherNumber: secretNumber){
  //....

The compareNumber basically transforms a compare check into an Enumeration:

    func compareNumber(number: Int, otherNumber: Int) -> Comparison{
        if number < otherNumber {
            return .Smaller
        } else if number > otherNumber {
            return .Greater
        }
        
        return .Equals
    }

Back to the switch statement of selectedNumber—it first checks whether the number inserted is the same as the secret number:

case .Equals:
var alert = UIAlertController(title: nil, 
              message: "You won in \(numGuesses) guesses!",
              preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", 
              style: UIAlertActionStyle.Default, 
              handler: { cmd in
                self.reset()
                self.numberTxtField.text = ""
              }))
            self.presentViewController(alert, 
              animated: true, completion: nil)

If this is the case, a popup with the number of guesses is presented, and when it is dismissed, all of the data is cleaned and the game starts again.

If the number is smaller, we calculate the lower bound again, and then we render the feedback labels:

        case .Smaller:
            lowerBound = max(lowerBound, number)
            messageLbl.text = "Your last guess was too low"
            numberTxtField.text = ""
            numGuesses++
            renderRange()
            renderNumGuesses()

If the number is greater, the code is similar, but instead of the lower bound, we calculate the upper bound:

        case .Greater:
            upperBound = min(upperBound, number)
            messageLbl.text = "Your last guess was too high"
            numberTxtField.text = ""
            numGuesses++
            renderRange()
            renderNumGuesses()
        }

Et voilà! With this simple code, we have implemented our app.

Note

You can download the code of the app from https://github.com/gscalzo/GuessTheNumber.

Summary

This was a really dense chapter because we squeezed in content, that usually needs at least a book to explain properly, in only tens of pages.

We took a quick look at Swift and its capabilities, starting from the definitions of variables and constants, and then how to define the control flow. After that, we moved on to structs and classes, seeing how they are similar in some ways, but profoundly different as philosophies. Finally, we created a simple game app, showing all the required steps in great detail.

Of course, simply after reading this chapter, nobody can be considered an expert in Swift and Xcode. However, the information here is enough to let you understand all of the code we'll be using in the upcoming chapters to build several kinds of apps.

In the next chapter, we'll continue to explore Swift and iOS by implementing another game—a memory game that will let us make use of the power of structs. You will also learn about some new things in UIKit.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image