Mobile - - By David Turnbull

Creating a ‘Hello World’ App with Swift

Back in June, Apple announced the Swift programming language and if you’re like me, it probably made you think

“Maybe now is the time I learnt how to develop applications for iOS devices and the Mac”

Of course, the real “best time” to learn Swift was a while ago, but there’s a lot to love about Swift compared to Objective-C:

  1. It’s modern.
  2. It’s clean.
  3. It’s safe.

It’s not without its flaws, it’s a young language after all, but those flaws are not so significant that a beginner developer shouldn’t start with Swift. Objective-C has years of real-world use, but Swift is the future.

To step into this future, we’re going to make a simple “Hello World” example in Swift, while covering the absolute basics of iOS development.

Let’s begin.

Prerequisites

For this tutorial, download the latest version of Xcode from the Mac App Store. This is the IDE we use to make iPhone and Mac applications. Also be aware that this tutorial is not a complete beginner’s guide to programming. I will assume a basic understanding of ideas like variables and functions.

Step 1: Create a Project

After opening Xcode, click on the “File” menu, hover over the “New” option, and then select “Project”. You should see something like this:

Creating a new project with Xcode

Here we see a number of templates for creating iOS applications. These templates all include some default code that can help save us time. We’ll choose the “Single View Application” option for now. This comes with the smallest amount of default code, making it the best option for learning the basics.

Click the “Next” button and fill out the following details:

  • Product Name. This is the name of your application.
  • Organization Name. Enter your name or your company’s name.
  • Organization Identifier. Usually, this is formatted as a reverse domain name (so something like com.davidturnbull).
  • Language. Set this to “Swift”.
  • Devices. Set this to “iPhone”.
  • Use Core Data. Leave this unchecked.

Click the “Next” button again. A dialog box will appear to save the project, so choose whatever location is convenient.

Once the project is saved, a range of different options will appear. This can make Xcode feel overwhelming, but rest assured, we can ignore most of what we see on the screen. For now we will only worry about the basics.

Step 2: Design an Interface

On the left side of the screen, we can see the “Navigator” pane. This is what we use to navigate the files in our project. There’s a few files that Xcode creates for us, but for the moment, click on the Main.storyboard file.

You should see the following:

XCode Screen Overview

Here, we see a white “View Controller” square, and when making an iPhone application, a view controller is basically equivalent to a screen. So if you open the “Clock” app on an iPhone, we can see it has four main screens, and therefore at least four view controllers:

  • World Clock
  • Alarm
  • Stopwatch
  • Timer

This isn’t a perfect definition, but for the time being, it’s fine to assume that view controllers are a fancier name for screens.

The weird thing about our view controller though is that it’s a square. But the iPhone itself isn’t square. What gives? Well, because different devices have different screen sizes, we are encouraged to design the interface so it can adapt to these different requirements.

To turn off this feature (it’s beyond the scope of this tutorial), complete the following steps:

  1. Click anywhere inside the white square to select the view controller.
  2. Select the “Attributes Inspector” from the right sidebar.
  3. Change the “Size” option to any of the “iPhone” options.

Because of this change, the view controller should now be rectangular.

Changing View size

At this point, we’ll make our interface mildly interesting by adding a button to the middle of it. To achieve this, take a look at the “Object Library”.

This library contains a range of objects we can drop into our interface, and if you scroll (or search) through the list, you’ll find a “Button” object:

XCode Object Library

Drag this button from the library and into the view controller. You might see blue lines appear, which helps our designs adhere to Apple’s Human Interface Guidelines. To change the button’s text, double-click the button and change it to “Click Me”.

With this button in place, click on the “Player” arrow in the top-left corner of Xcode. This will run our application inside an iOS simulator, so we can get a better idea of how the application looks on a simulated device. After a few moments loading, you should see something like the below:

App Preview

To test the application on a range of simulated devices, choose between the available options in the “schemes” menu next to the play button:

Schemes Menu

Step 3: Write Swift Code

To start writing some Swift code, open the “Assistant Editor”. You can find the button for this in the top-right corner of the screen. After clicking the button, a file with some code will appear. This is the ViewController.swift file, and it contains code that specifically relates to our view controller.

For the moment, ignore all of the code except for this part:

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

Here, we have function called viewDidLoad, and this function will execute as soon as our view loads. Because our application only has one view, the code will execute as soon as the application loads.

To see this in action, write the following at the bottom of the function:

println("Hello world")

The println function is used to output something to the console. In this case, we’re outputting text with “Hello world”. Note that we haven’t used a semi-colon to end the statement. This is because Swift doesn’t expect a semi-colon. You can write them, but they’re unnecessary.

Run the simulator again and notice that, when the application loads, another pane appears at the bottom of the Xcode window. This is the “Debug” pane and, on the right side of it, we can see the console with our “Hello world” text.

Debug Console

Step 4: Create an Action

The next step is to make a message appear in the console when a user clicks on the “Click Me” button, rather than when the view loads.

To achieve this:

  1. Hold down the CTRL key.
  2. Click on the “Click Me” button.
  3. Drag the cursor into the ViewController.swift file.

It’s best to drag the cursor just above the viewDidLoad function:

A window will appear with a range of options. We’ll change two of them:

  1. Set the “Connection” option to “Action”.
  2. Set the “Name” option to “buttonPressed”.

Here, we’re creating an action, and actions allow interface elements to respond to events. In this case, the “Click Me” button will respond to the “Touch Up Inside” event. (This is just a common “tap” event.)

As for the “Name” option, this allows us to reference the action. So our action will be referenced as buttonPressed.

After clicking the “Connect” button, the code below appear in the Swift file:

@IBAction func buttonPressed(sender: AnyObject) {
}

There’s a few things going on with this buttonPressed function but the important thing to know is that, when because we attached this action to our button, the code in this function will execute when the button is tapped.

To demonstrate this, add a println function inside our button’s function:

@IBAction func buttonPressed(sender: AnyObject) {
    println("You clicked the button")
}

So now, if we run the simulator, the “You clicked the button” message will appear in the console each time the user clicks the button.

Step 5: Create an Outlet

Last up, we’re going to make the “You clicked the button” text appear inside the interface so users can actually see it, and to achieve this, we’re going to start playing around with outlets.

Outlets allow us to modify parts of our interface through code. To see how they work, drag a “Label” object from the library into the interface. This object is simply used to display a string of text.

Then repeat the steps we went through with the button:

  1. Hold down the CTRL key.
  2. Click on the label object we just created.
  3. Drag the cursor into the ViewController.swift file.

This time, don’t change the “Connection” option. Just leave it set to “Outlet”. The only thing you should change is the “Name” option, because this acts as a reference for our object. I’ve named mine “ourLabel”.

You should see the following appear inside our code:

@IBOutlet var ourLabel: UILabel!

Because of this statement, we can now reference this ourLabel variable from within our code, allowing us to modify our label programmatically.

So inside the buttonPressed function, remove the println function and replace it with the following:

ourLabel.text = "You clicked the button"

Here we’re doing a few things:

  1. We reference the ourLabel object.

  2. We modify its text property.

  3. We set the text property to this “You clicked the button” string.

As a result, if we run the simulator again, clicking the “Click Me” button will change the value of the label to this static text.

Conclusion

In this tutorial, we’ve only covered the absolute basics of making an iOS application with Swift. You probably have a lot of lingering questions, and that’s fine, iOS development is a big topic and questions are your friend.

That said, a lot can be achieved with even just this basic understanding of outlets and actions, so here’s a challenge:

Add a text field to the interface and make it so whenever the user types into this field, it’s content will appear inside the label when they press the button. If you’re not sure where to start, note that the text field will need to be an outlet.

Sponsors