Hello Swift!

We all knew Apple is going to release new features and APIs at WWDC this year and half way through the keynote there were already lots of new and exciting announcements. And then, out of the blue, Swift came along and the world will never be the same. The brand new programming language is definitely the most exciting thing announced this year and I couldn’t wait for the Xcode download to finish so I can play with it.

When learning a new programming language you usually start from “Hello World!”. Apple provided a great book for Swift and that starts precisely with “Hello World!”.

println("Hello World!")

However, that’s not very exciting and also it’s not an app. So instead of printing “Hello World!” to the console, let’s create an app using only Swift, that allows you to enter a name, press a button and see a nice greeting on the screen.

Before we start you will need the beta version of Xcode 6 which you can download from the iOS developer centre.

Let’s create a new project (File -> New -> New Project or the keyboard shortcut ⇧⌘N ). A single view application will do.

SingleViewAppGive it the name HelloSwift and make sure you select the language and choose Swift. Notice that you’re not asked for class prefix anymore. Gone are the days of duplicate symbol errors because of same class name, Apple introduced bundles.


Next choose where to store the project and then you’re ready to go.

As usual Xcode creates a few template files for us, AppDelegate.swift and ViewController.swift. When using Swift you don’t have headers, all the code goes in the same .swift file. We still have a storyboard file and Xcode 6 allows us to do some extra magic. Running the app now will show an empty view, so let’s start adding our own UI controls.

When opening the storyboard we will notice that the view controller created by Xcode has a different size, neither iPhone or iPad size. This is related to the extra magic that I was talking about. Let’s ignore this for now and just drag a label, a text field and a button to our view. Align them so that everything looks like this:


We’re going to setup these controls in our view controller so we can write more Swift code and get used to it, but in order to do that we need to create outlets. At least that’s what you would have done in Objective C. This part stayed the same in Swift and it’s nice and easy to bring up the Assistant Editor view. This will show our .swift file and we can select each control in turn, hold Ctrl and drag to the file on the right window (it should be our ViewController.swift file).


You should now have 3 outlets:

@IBOutlet var helloLabel : UILabel
@IBOutlet var nameTextField : UITextField
@IBOutlet var sayHelloButton : UIButton

This part is very similar to what we were doing in Objective C and you probably recognise the IBOutlet keyword. We also notice one new keyword in our ViewController.swift and that is override. It is used whenever you override a method of your super class and it’s suppose to avoid situations where you override methods without realising it. Swift is trying to prevent common developer mistakes.

Now that we have our outlets let’s start customising them. We’ll create a method to setup our UI. In Swift the method declaration will look like this:

func setupUI() {

This is a simple method that doesn’t take any parameters and doesn’t return anything. We want  the default text for our label to be “Hello Swift!”, text colour to be red and centre aligned.

helloLabel.text = "Hello Swift!"
helloLabel.textColor = UIColor.redColor()
helloLabel.textAlignment = NSTextAlignment.Center

Conceptually it’s the same thing we would do in Objective C, just different syntax. We don’t need semicolons at the end of the lines and you don’t need to use @ before string literals. And instead of sending a message to UIColor to give us a red colour we just call the convenience methods provided. Let’s continue by adding some placeholder text for our text field:

nameTextField.placeholder = "Enter your name"

Next, let’s change the title of the button.

sayHelloButton.setTitle("Say Hello", forState: .Normal)

Notice that it’s enough for us to say .Normal instead of UIControlState.Normal. Swift will infer from the context what we mean and allow us to use this “shortcut”. We’re done with the initial setup of our UI, but before we see how our UI will look we need to actually call the method we’ve created. So let’s call this method from viewDidLoad:

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.

Before we run our app let’s add an action for our button. In Interface Builder, bring up the Assistant editor and Ctrl drag from the UIButton to the view controller. Change from Outlet to Action and name the method sayHelloAction:


We want to change the text of the label to use the text entered in the text field or to display an alert view prompting the user to enter some text if no name was entered.

@IBAction func sayHelloAction(sender : AnyObject) {
    let name = nameTextField.text

    if name.isEmpty {

        let alert = UIAlertController(title: "Error", message: "Please enter a name",
                preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,
                handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    } else {
        helloLabel.text = "Hello \(name)!"

First we got the text from the text field and stored it in a constant because we are not modifying that and in Swift it is recommended to use constants whenever you can. Next we’re checking if the string we got back is empty and if it is we want to display an alert view. UIAlertView is deprecated in iOS 8 and trying to use its init method crashes the app (at least in Beta 2 version of iOS 8), so instead we are using UIAlertController. If the string is not empty then we’re just using string interpolation to construct the new text for the label.

When we run our app on an iPhone 5s simulator we see this:


This is not exactly what we expected. To fix this we need to talk about a new feature called size classes.

One Reply to “Hello Swift!”

Leave a Reply

Your email address will not be published. Required fields are marked *