Beginning iOS 10 Programming with Swift

Chapter 3
Hello World! Build Your First App in Swift

Learn by doing. Theory is nice but nothing replaces actual experience.

– Tony Hsieh

By now you should have installed Xcode 8 and some understandings of Swift language. If you haven't done so, check out the first chapter about what you need to begin iOS programming. We'll use Xcode 8.0 (or up) to work on all exercises in this book.

You may have heard of the "Hello World" program if you have read any programming book before. Hello World is a program for the first-time programmer to create. It's a very simple program that outputs "Hello, World" on the screen of a device. It's a tradition in the programming world. Let's follow the programming tradition and create a "Hello World" app using Xcode.

Despite its simplicity, the "Hello World" program serves a few purposes:

  • It gives you an overview of the syntax and structure of Swift, the new programming language of iOS.
  • It also gives you a basic introduction to the Xcode environment. You'll learn how to create an Xcode project and lay out your user interface using Interface Builder. Even if you've used Xcode before, you'll learn what's new in the latest version of Xcode.
  • You'll learn how to compile a program, build the app and test it using the built-in simulator.
  • Lastly, it makes you think programming is not difficult. I don't want to scare you away from learning programming. It'll be fun.

Your First App

Your first app, as displayed in figure 3-1, is very simple and just shows a "Hello World" button. When a user taps the button, the app shows a welcome message. That's it. Extremely simple but it helps you kick off your iOS programming journey.

Figure 3-1. HelloWorld App
Figure 3-1. HelloWorld App

When you're building your first app, please keep one thing in mind: forget about the code. I'm quite sure that you will find some of the Swift code difficult to understand. No worries. Just focus on the exercise, and get yourself familarized with the Xcode environment. We will talk about the code in the next chapter.

Let's Jump Right Into the Project

First, open Xcode. Once launched, Xcode displays a welcome dialog. From here, choose "Create a new Xcode project" to start a new project:

Figure 3-2. Xcode - Welcome Dialog
Figure 3-2. Xcode - Welcome Dialog

Xcode shows various project templates for selection. The Single View Application template is the most common template for creating an iOS app. So, choose iOS > Single View Application and click Next.

Figure 3-3. Xcode Project Template Selection
Figure 3-3. Xcode Project Template Selection

This brings you to the next screen to fill in all the necessary options for your project.

Figure 3-4. Options for your Hello World project
Figure 3-4. Options for your Hello World project

You can simply fill in the options as follows:

  • Product Name: HelloWorld – This is the name of your app.

  • Team: Just leave it as it is. If you click the button, it will prompt you to sign in with your Apple ID. For your first app, just skip this step.

  • Organization Name: AppCoda – It's the name of your organization. You may use your name if you're not building an app for your organization.

  • Organization Identifier: com.appcoda – It's actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use "com.appcoda" or just fill in "edu.self".

  • Bundle Identifier: com.appcoda.HelloWorld - It's a unique identifier of your app, which is used during app submission. You do not need to fill in this option. Xcode automatically generates it for you.

  • Language: Swift – Xcode 8 supports both Objective-C and Swift for app development. As this book is about Swift, we'll use Swift to develop the project.

  • Devices: iPhone – Select "iPhone" for this project. Let's keep things simple and build the app for the iPhone device only.

  • Use Core Data: [unchecked] – Do not select this option. You do not need Core Data for this simple project. We'll explain Core Data in later chapters.

  • Include Unit Tests: [unchecked] – Do not select this option. You do not need unit tests for this simple project.

  • Include UI Tests: [unchecked] – Do not select this option. You do not need UI tests for this simple project.

Click "Next" to continue. Xcode then asks you where to save the "HelloWorld" project. Pick any folder (e.g. Desktop) on your Mac. You may notice there is an option for source control. Just deselect it. We do not need to use the option in this book. Click "Create" to continue.

Figure 3-5. Choose a folder and save your project
Figure 3-5. Choose a folder and save your project

After you confirm, Xcode automatically creates the "Hello World" project. The screen will look like the screenshot shown in figure 3-6.

Figure 3-6. Main Xcode Window for HelloWorld Project

Familiarize Yourself with Xcode Workspace

Before we start to write some code, let's take a few minutes to have a quick look at the Xcode workspace environment. In the left pane is the project navigator. You can find all your project files in this area. The center part of the workspace is the editor area. You do all the editing stuff here (such as editing the project setting, source code file, user interface) in this area.

Depending on the type of file, Xcode shows you different interfaces in the editor area. For instance, if you select ViewController.swift in the project navigator, Xcode displays the source code in the center area (see figure 3-7). If you select Main.storyboard, which is the file for storing user interface, Xcode shows you the visual editor for storyboard (see figure 3-8).

Figure 3-7. Xcode Workspace with Source Code Editor
Figure 3-7. Xcode Workspace with Source Code Editor
Figure 3-8 . Xcode Workspace with Storyboard Editor
Figure 3-8 . Xcode Workspace with Storyboard Editor

The rightmost pane is the utility area. This area displays the properties of the file and allows you to access Quick Help. If Xcode doesn't show this area, you can select the rightmost button in the toolbar (at the top-right corner) to enable it.

Figure 3-9. Show/hide the content areas of your workspace
Figure 3-9. Show/hide the content areas of your workspace

The middle view button of the view selector is deselected by default. If you click on it, Xcode displays the debug area right below the editor area. The debug area, as its name suggests, is used for showing debug messages. We'll talk about that in a later chapter, so don't worry if you do not understand what each area is for.

Run Your App for the First Time

Until now, we haven't written a single line of code. Even so, you can run your app using the built-in simulator. This will give you an idea how to build and test your app in Xcode. In the toolbar you should see the Run button.

Figure 3-10. Run and Stop Buttons in Xcode
Figure 3-10. Run and Stop Buttons in Xcode

The Run button in Xcode is used to build an app and run it in the selected simulator. By default, the Simulator is set to iPhone SE. If you click the iPhone SE button, you'll see a list of available simulators such as iPhone 4s and iPhone 6s Plus. Let's select iPhone 6 as the Simulator, and give it a try.

Once selected, you can click the Run button to load your app in the Simulator. Figure 3-11 shows the simulator of an iPhone 6.

Figure 3-11. The Simulator
Figure 3-11. The Simulator
Quick tip: On non-retina Mac, it may not be able to show the full simulator window. You can select the simulator, and press command+2 or command+3 to scale it down. Alternatively, you can go up to the menu, and choose Window > Scale.

A white screen with nothing inside?! That's normal. So far we haven't designed the user interface or written any lines of code. This is why the simulator shows a blank screen. To terminate the app, simply hit the Stop button in the toolbar.

Try to select another simulator (e.g. iPhone SE) and run the app. Just play around with it to get yourself familiarize with the Xcode development environment.

A Quick Walkthrough of Interface Builder

Now that you have a basic idea of the Xcode development environment, let's move on and design the user interface of your first app. In the project navigator, select the Main.storyboard file. Xcode then brings up a visual editor for storyboards, known as Interface Builder.

The Interface Builder editor provides a visual way for you to create and design an app's UI. Not only can you use it to design individual view (or screen), the Interface Builder's storyboard designer lets you lay out multiple views, and chain them together using different types of transitions to create the complete user interface. All these can be done without writing a line of code.

Figure 3-12 . The Interface Builder Editor
Figure 3-12 . The Interface Builder Editor

The Object library at the lower right pane contains all the available UI objects such as button, label, image view for you to design your user interface. If you can't see the Object library, click the Show the Object library button, as displayed in figure 3-12, to reveal it. You can view the Object library in two difference modes: list view and icon view. I prefer to use icon view in this book. But if you want to change to the list view mode, simply use the toggle button to switch between them.

Since we chose to use the Single View Application template during project creation, Xcode generated a default view controller scene in the storyboard. In your Interface Builder, you should see a view controller in the editor area. This view controller is where you design the app's user interface. Each screen of an app is usually represented by a view controller. Interface Builder allows you to add multiple view controllers to the storyboard and link them up. Later in this book, we will further discuss about that. Meanwhile, focus on learning how to use Interface Builder to lay out the UI for that view controller.

What is a Scene?

A scene in storyboard represents a view controller and its views. When developing iOS apps, views are the basic building blocks for creating your user interface. Each type of view has its own function. For instance, the view you find in the storyboard is a container view for holding other views such as buttons, labels, image views, etc. A view controller is designed to manage its associated view and subviews (e.g. button and label). If you are confused about the relationship between views and view controllers, no worries. We will discuss how a view and view controller work together in the later chapters.

The Document Outline view of the Interface Builder editor shows you an overview of all scenes and the objects under a specific scene. The outline view is very useful when you want to select a particular object in the storyboard. If the outline view doesn't appear on screen, use the toggle button (see figure 3-12) to enable/disable the outline view.

Lastly, there is a configuration bar in the Interface Builder. To reveal the bar, place the mouse cursor on View as: iPhone 6s, and then single-click on it. The configuration bar is a new feature in Xcode 8 that lets you live preview your app UI on different devices. Furthermore, you can use the + and - buttons to zoom in/out the storyboard. We will talk about this new feature later on.

Figure 3-13 . The new configuration bar in Xcode 8
Figure 3-13 . The new configuration bar in Xcode 8

Designing the User Interface

Now we are going to design the app's user interface. First, we will add a Hello World button to the view. At the bottom part of the utility area, it shows the Object library. Here, you can choose any of the UI objects, and drag-and-drop them into the view. If you're in the icon view mode of the Object library, you can click on any of the objects to reveal the detailed description.

Okay, it's time to add a button to the view. All you need to do is drag a Button object from the Object library to the view.

Figure 3-14. Drag the Button to the View
Figure 3-14. Drag the Button to the View

As you drag the Button object to the view, you'll see a set of horizontal and vertical guides if the button is centered. Stop dragging, and release your button to place the Button object there.

Next, let's rename the button. To edit the label of the button, double-click it and name it "Hello World". After the change, you may need to center the button again.

Figure 3-15. Renaming the button
Figure 3-15. Renaming the button

Great! You're now ready to test your app. Select the iPhone 6/6s simulator and hit the Run button to run the project, you should see a Hello World button in the simulator as shown in figure 3-16. Cool, right?

However, when you tap the button, it shows nothing. We'll need to add a few lines of code to display the "Hello, World" message.

Figure 3-16. Hello World app with a Button
Figure 3-16. Hello World app with a Button
Quick note: This is the beauty of iOS development. The code and user interface of an app are separated. You're free to design your user interface in Interface Builder and prototype an app without writing any lines of code. 

Coding the Hello World Button

Now that you've completed the UI of the HelloWorld app, it's time to write some code. In the project navigator, you should find the ViewController.swift file. Because we initially selected the Single View Application project template, Xcode already generated a ViewController class in the ViewController.swift file. This file is actually associated with the view controller in the storyboard. In order to display a message when the button is tapped, we'll add some code to the file.

Swift versus Objective-C

If you have written code in Objective-C before, one big change in Swift is the consolidation of header (.h) and implementation file (.m). All the information of a particular class is now stored in a single .swift file.

Select the ViewController.swift file and the editor area immediately displays the source code. Type the following lines of code in the ViewController class:

@IBAction func showMessage() {
    let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    present(alertController, animated: true, completion: nil)
}
Quick note: I encourage you to type the code, rather than copy & paste it.

Your source code should look like this after editing:

import UIKit

class ViewController: UIViewController {

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func showMessage() {
        let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        present(alertController, animated: true, completion: nil)
    }
}

What you have just done is added a showMessage() method in the ViewController class. The Swift code within the method is new to you. I will explain it to you in the next chapter. Meanwhile, just consider the showMessage() as an action. When this action is called, the block of code will instruct iOS to display a "Hello World" message on screen.

Connecting the User Interface with Code

I said before that the beauty of iOS development is the separation of code (.swift file) and user interface (storyboards). But how can we establish the relationship between our source code and user interface?

To be specific for this demo, the question is:

  • How can we connect the "Hello World" button in the storyboard with the showMessage() method in the ViewController class?

You need to establish a connection between the "Hello World" button and the showMessage() method you've just added, such that the app responds when someone taps the Hello World button.

Now select Main.storyboard to switch back to the Interface Builder. Press and hold the control key of the keyboard, click the "Hello World" button and drag it to the View Controller icon. Release both buttons (mouse + keyboard) and a pop-up shows the showMessage option under Sent Events. Select it to make a connection between the button and showMessage action.

Figure 3-17. Drag to the View Controller icon (left), a pop-over menu appears when releasing the buttons (right)
Figure 3-17. Drag to the View Controller icon (left), a pop-over menu appears when releasing the buttons (right)

Test Your App

That's it! You're now ready to test your first app. Just hit the Run button. If everything is correct, your app should run properly in the simulator. This time, the app displays a welcome message when you tap the Hello World button.

Figure 3-18. Hello World app
Figure 3-18. Hello World app

Changing the Button Color

There is one more thing I want to discuss with you before ending the chapter. As mentioned before, you do not need to write code to customize a UI control. Here, I want to show you how easy it is to change the properties (e.g. color) of a button.

Select the "Hello World" button and then click the Attributes inspector under the Utility area. You'll be able to access the properties of the button. Here, you can change the font, text color, background color, etc. Try to change the text color (under Button section) to white and background (scroll down and you'll find it under View section) to red or whatever color you want.

Figure 3-19. Changing the color of the Hello World button
Figure 3-19. Changing the color of the Hello World button

Run the project again and see what you get.

Your Exercise

Not only can you change the color of a button, you can modify the font type and size in the Attributes inspector by setting the Font option. Your task is to continue to work on the project and create a user interface like figure 3-20. When a user taps any of the buttons, the app displays the same Hello World message.

Figure 3-20. Your exercise
Figure 3-20. Your exercise

To give you some hints, here are the things you will need to:

  1. Resize the "Hello World" button and change its font size to 50 points. Also, set the font style from Regular to Medium.
  2. Add three more buttons. Each of them has an emoji icon as its title. To key in emoji characters, you can hold down control+command and then press spacebar.
  3. Establish a connection between the buttons and the showMessage() method.

What's Coming Next

Congratulations! You've built your first iPhone app. It's a simple app, but I believe you already have a better understanding of Xcode and understand how an app is built. It's easier than you thought, right?

In the next chapter, we'll discuss the details of the Hello World app and explain how everything works together.

For reference, you can download the complete Xcode project from http://www.appcoda.com/resources/swift3/HelloWorld.zip.

For the solution of the exercise, you can download it from http://www.appcoda.com/resources/swift3/HelloWorldExercise.zip.