20 Cocoa Apps Challenge


App 02: Guess The Number

  • Data type conversion
  • if else
  • Random number generator
  • NSColor

UI Flow

Controls, Outlets, and Actions

Our Cocoa app contains three basic controls:
  • Label (of type NSTextField)
  • Text field (of type NSTextField)
  • Button (of type NSButton)
Note that in Cocoa, labels are NSTextField, not UILabel The label and text field are connected as outlets while the button is connected as an action


The app generates a random number from 1 to 12. The app then compares the generated random number (a UInt32) with the number inputted into the text field (a String).

Data type conversion

But before they can be compared properly, they both must have the same type. So our solution is to convert UInt32 into a String so that we compare the values of both as Strings.

    String(randomNumber) == numField.text
Note that type conversion is not the same as type casting.

if else

The message label's text depends upon the result of the comparison. If random number has the same value as in the text field, then the guess was correct. Otherwise, the guess was incorrect.

Random Number Generator

arc4random_uniform(N) is a random number generator in OS X. You give it an upperbound N and it returns random numbers between 0 and N - 1.
For example, to generate random numbers between 0 and 99:
arc4random_uniform( 100 )   // 0 … (100 - 1)
Since our Cocoa app requires a random number between 1 and 12, we do this:
arc4random_uniform( 12 ) + 1   // (0 … (12 - 1)) + 1
This just adds 1 to whatever value is returned by the random generator so that the result will always be 1 more than the returned original value.


How To


//  AppDelegate.swift
//  Guess The Number
//  Created by Arthur Kho (github.com/islandjoe) on 08/16.
//  MIT License
//  Copyright (c) 2016 Arthur Kho

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

  /// Random number between 1 and 12
  var randomNumber = arc4random_uniform( 12 ) + 1

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var message: NSTextField!
  @IBOutlet weak var numField: NSTextField!

  @IBAction func guess(sender: NSButton) {

    let theGuess = numField.stringValue
    let correct  = String(randomNumber)

    if theGuess == correct {

      message.stringValue = "Correct!"
      message.textColor = NSColor.greenColor()

    else {

      message.stringValue = "Wrong. Guess again."
      message.textColor = NSColor.redColor()


20 Cocoa Apps Challenge