Hello World using Xcode and Swift

Swift logo

“Hello World using Xcode and Swift” is the first post about Swift where I’m starting to create a simple but real app. I wrote a couple of posts before as introduction to Swift:

Finally, it is time to use Xcode and practice. Here, you have the video to help you to understand visually what I’m doing and explain in this post. Please subscribe my YouTube channel!

The source code of this basic project is on GitHub.

Create a new Xcode project

So, it is time to become friends with Xcode. Then, go ahead and open it. At the time of writing, the Xcode version is the number 12. But make sure you are suing the latest official version of Xcode from the Mac App Store.

In the “Welcome to Xcode” screen, you can choose either get started with a playground which is a great way to explore the Swift language. The next option is creating a new Xcode project where you create an app for iPhone, iPad, Mac, Apple Watch or Apple TV.

Xcode Welcome Screen
Xcode Welcome Screen

Also, you can open or clone an existing project. I won’t cover those two options here but there are pretty straightforward.

What we have to do now is to create a new project. So, click on “Create a new Xcode project“. Where click on it, Xcode shows a new popup window that’s asks what kind of project do you want to make, whether iOS, watchOS, tvOS, macOS or Multiplatform.

  • iOS includes apps for the iPhone, iPad, iPod Touch
  • watchOS is for Apple Watch apps
  • tvOS is for Apple TV apps
  • macOS is for Mac apps on the desktop
  • Multiplatform is if you want to make an app that works across different platforms
Xcode - Choose a template for your new project - Hello World using Xcode and Swift
Xcode – Choose a template for your new project

So, for an iOS app, there are a lots of different templates that you can start to use. The templates help you to get started with some boilerplate code. For the purpose of the first simple example “Hello World using Xcode and Swift”, we want to use App option. So, App template is a blank starting point for almost every app.

Now, we have to make some choices with the settings:

  • Product Name: it is the name of your project. In this case HelloWorld
  • Team: you can select None but later Xcode will give you an error. You have to set up at least an developer account to build your project and run it in a simulator or in your machine
  • Organization Identifier: the purpose of it is to identify in a unique way an app. Normally, people put the reverse of the website they own. For example, my website is puresourcecode.com and the Organisation Identifier is com.puresourcecode. If you don’t have a website, you can put a random one like for example com.lastname.firstname
  • Interface: select Storyboard
  • Life Cycle: select UIKit App Delegate
  • Language: select Swift
  • Use Core Data and Include Tests leave all boxes unchecked
Xcode - Choose options for your new project - Hello World using Xcode and Swift
Xcode – Choose options for your new project

An important thing about the option Interface. You can choose between SwiftUI and Storyboard. SwiftUI is a new way of implementing user interfaces introduces in Xcode 11 in iOS 13. It will be the best way to make iOS apps eventually but there are certain things that it can’t handle yet. If you try to make a professional app with SwiftUI, you find yourself going back to storyboard elements and it can get messy. So, we will select storyboard which had been the establish way of designing interfaces.

Now, press the button Next and Xcode asks where you want to save your project. In my personal experience, I prefer to create a Projects folder for all my projects. For now, if you want, you can use the Documents folder. Then, you have your new Xcode window with the project.

First HelloWorld overview - Hello World using Xcode and Swift
First HelloWorld overview

Also, there is another option “Create Git repository on my Mac“. If you want to know more about Git, please read one of the following documents.

Folder file structure

So, on the left side of Xcode, you have the folder-file structure of the project like in the following image. This is the representation of what you have on your disk.

HelloWorld folder file structure - Hello World using Xcode and Swift
HelloWorld folder file structure

So, on the disk, we have our HelloWorld project folder at the root and another HelloWorld folder with more files inside. If you want to open this project again, you can double-click on HelloWorld.xcodeproj and automatically the project will be open in Xcode.

HelloWorld on disk - Hello World using Xcode and Swift
HelloWorld on disk

Xcode will take the name of your project and put that in a folder that is the container of the entire project.

HelloWorld on disk - Explore HelloWorld sub-folder - Hello World using Xcode and Swift
HelloWorld on disk – Explore HelloWorld sub-folder

Now, a quick introduction to the files you have in the project:

  • Main.storyboard: this is where all the visual part of our code happens. Here, we add all the UI elements to make our apps
  • ViewController.swift and AppDelegate.swift: where we are going to be typing out some code to make things happen
  • Assets.xcassets: to store resources that our app uses like images, sounds, fonts, videos and so on
  • Info.plist (Information Property List): contains metadata settings for your app such as app name, version and permissions

Project settings

Before going on, have a look to the project settings. If you click on the root project file, you can see the General settings for your app. Do you remember when we created a new project? All the basic settings are here and you can change them.

Project settings: General
Project settings: General

Under the Signing & Capabilities tab is also where we had to specify them Team field. Again, you can come back here and change it. For example, we have not specified Team. Here, you can go back and change when you want to submit your app to the App Store.

Project settings: Signing & Capabilities
Project settings: Signing & Capabilities

Change the views

So, there are 2 main files we will work with for now: ViewController.swift and Main.storyboard. As you can understand from the extensions, ViewController.swift is where the programming code of our app resides and Main.storyboard is the visual part of our app.

To begin adding visuals, click on Main.storyboard.

Main.storyboard for your project
Main.storyboard for your project

Now, we want to add a Label to the storyboard. Labels are used to represent texts. Now, click on the + on the top right and the list of visual object will appear.

Add a new visual to the Main.storyboard
Add a new visual to the Main.storyboard

Now, click on the item Label and drag it on the Main.storyboard. Xcode helps you to understand where you are positioning the label with rules (the blue line you see). When you move the label in the position you want, drop it.

After that, you can test to see how your app will look different on different devices. For that, at the bottom of the storyboard, you find a View as panel. Change device, appearance and orientation. Then, let’s change back to the iPhone 11 device.

Test how your app looks in different devices
Test how your app looks in different devices

So, you will realise that for different devices, the app looks different. That is if we try to center our label on an iPhone 11 and when we change the display to an iPhone 8 plus or an iPhone 4s, the centering goes off. To fix these, we will need to add constraints.

To add new constraints, select the label and click on the Xcode constraint icon. Then, we specify 2 constraints of 10 from the left and 10 from the right after which select Add 2 Constraints.

Add new constraints
Add new constraints

What this means is that we constrained the label to begin with a margin of 10 from the left and end with a margin of 10 from the right. To center the text, selling the label and in the Attributes inspector, select centre for alignment. Thanks to constraints, our label and text will now be entered regardless of which device we select now.

Now, add a constraint from the top of 400.

Outlets

So, outlets are what connect the visual part (storyboard) to the code part (Swift files) of our app. We use an outlet in our Swift file to get access to a label in the storyboard. To begin creating an outlet for our app, it is useful to switch to the Split screen mode. To do so, select the View Controller in the storyboard and click on the adjust editor options icon Adjust Editor Options icon. Then, select Assistant.

Outlets: Adjust Editor Options and select Assistant
Outlets: Adjust Editor Options and select Assistant

At this point, there should be a split screen showing your storyboard on the left and the code file for ViewController.swift on the right. Now, select the Label and hold down the Control key and click drag to the ViewController.swift file just above the viewDidLoad() function.

Outlet between ViewController.swift and the code file
Outlet between ViewController.swift and the code file

Now, release the mouse and you see the window where you can enter the Name of the label outlet. Type firstLabel and click Connect. So, Xcode is generating code for you.

Outlet window with Name
Outlet window with Name
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var firstLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

Xcode has created for us a variable called firstLabel that refers to the label on the storyboard. With this, we have established access to the label from ViewController.swift. This allows us to access the label and control attributes of the field. For example, add the line below:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var firstLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        firstLabel.text = "Hello world!"
    }
}

Finally, we have the Hello World using Xcode and Swift. We will now run our app to see the changes clicking on the Xcode run icon icon. The result of your first app is in the following screenshot.

First run of Hello World!
First run of Hello World!

So, the first Hello World using Xcode and Swift is running! Now, I want to add a bit more object and interaction in the application. I’m going to add a Button.

Buttons

Hello World using Xcode and Swift is looking good but it is not enough to have a decent app. Apart from labels, buttons are another object in the UI that it is quite common. User click on buttons which in turn lead to action calling specific code. So, go back to the storyboard and drag a button into the View Controller. Now, apply 2 constraints to the button like the label: 10 to the left and 10 to the right.

The constraints are applied for the left and right but what about the distance between the label and the button? We have to fix it. So, select the button, hold down the Control key, click drag onto the label and select Vertical Spacing.

Apply the vertical spacing
Apply the vertical spacing

Vertical spacing means that there should always have the same amount of vertical space between these two visual controls across across different devices.

Button actions

To create an action for our button, similar to how we created an outlet for the label, select the button, hold the Control key down, and click drag over the Swift code just after the viewDidLoad() method.

Create an action for a Button
Create an action for a Button

A popup with connection Action will appear. Name the action buttonTapped and click Connect.

buttonTapped connection action
buttonTapped connection action

So, Xcode has created for us the code for the action. When a user clicks on this button, the event buttonTapped will be fired. How do we know if it is working? Add this code in the buttonTapped function

@IBAction func buttonTapped(_ sender: Any) {
    print("Button tapped")
}

Now, run the application and click on the button. In the output window in Xcode, you can see the text.

buttonTapped output in the console
buttonTapped output in the console

Counter

Before finishing the first Hello World using Xcode and Swift, I want to add a little bit of code. Think about a simple counter app: I want to count every time you click on the button and display the number of tap in a label.

First of all, we have to define a variable to save the number of click. I’m calling this variable count.

import UIKit

class ViewController: UIViewController {
    
    var count = 0
    @IBOutlet weak var myFirstLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myFirstLabel.text="Hello world!"
    }
    
    @IBAction func buttonTapped(_ sender: Any) {
        print("Button tapped")
    }
}

Then, when we tap the button the app has to increment the variable count by 1. So, I want to display the value in the label. The buttonTapped changes like that:

@IBAction func buttonTapped(_ sender: Any) {
    count = count + 1
    firstLabel.text = String(count)
}

Because the label accepts only string, we have to convert the variable count in a String. Also, when the app starts, we want to display the value of the count.

override func viewDidLoad() {
    super.viewDidLoad()
    firstLabel.text = String(count)
}

So, all together the code is:

import UIKit

class ViewController: UIViewController {
    
    var count = 0
    @IBOutlet weak var firstLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        firstLabel.text = String(count)
    }
    
    @IBAction func buttonTapped(_ sender: Any) {
        count = count + 1
        firstLabel.text = String(count)
    }
}

Now, run the application and be happy!

The counter is complete
The counter is complete

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.