Swift is a programming language used to write apps and games for iPhone, iPad, Mac, Apple Watch and more; Apple designed Swift explicitly to get the fastest and most efficient performance from devices, and Swift 4 expands upon its already impressive feature set. In this article we show how to use Swift 4, explain why you should, and outline all the new features in this version of the language.

For a broader overview, take a look at our Complete guide to programming on a Mac. And if you're running an older rig and need the previous version of the language, see How to write apps in Swift 3.

Overview of Swift 4

Swift 4 is a new version of the Swift programming language developed by Apple for iOS and macOS development, adopting the best of C and Objective-C without the constraints of C compatibility. It uses the same runtime as the existing Obj-C system on macOS and iOS, which enables Swift programs to run on many existing iOS 6 and OS X 10.8 platforms.

  • Swift 4 makes use of safe programming patterns.
  • Swift 4 provides modern programming features.
  • Swift 4 provides seamless access to existing Cocoa frameworks.
  • Swift 4 unifies the procedural and object-oriented portions of the language.

New features in Swift 4

Let's look at the new elements in Swift 4 in more detail.

Strings

String now conforms to Collection protocol, and you can iterate over String directly. This also means you can use any Collection methods and properties on String, like count, isEmpty, map(), filter(), index(of:) etc.

How to make apps & games in Swift 4: Hello Playground

Swift 4 takes a completely different approach for multiple line strings by using triple quotes instead, so you don't have to escape double quotes any more:

How to make apps in Swift 4: Triple quotes

JSON Encoding and Decoding

Swift 4 simplifies the whole JSON archival and serialisation process you were used to in Swift 3. Now you only have to make your custom types implement the Codable protocol - which combines both the Encodable and Decodable ones.

How to make apps in Swift 4: JSON

Smarter Key Paths

Swift 4 makes it easier to access an object's properties with key paths.

How to make apps & games in Swift 4

Mixing Classes with Protocols

You can combine protocols together in Swift 3 when creating constants and variables. Swift 4 goes one step further and lets you add classes to the mix using the same syntax. You may constrain a certain object to a class and a protocol in just one go the same way as in Objective-C.

swap vs swapAt

The swap(_:_:) mutating method in Swift 3 takes two elements of a certain array and swaps them on the spot. This solution has one major drawback: the swapped elements are passed to the function as input parameters so that it can access them directly.

Swift 4 takes a totally different approach by replacing the method with a swapAt(_:_:) which takes the two elements' corresponding indices and swaps them just as before.

Dictionaries and Sets

You can use the dictionary's init(uniqueKeysWithValues:) initialiser to create a brand-new dictionary from a tuples array.

How to make apps & games in Swift 4: Dictionaries and Sets

Why should you code in Swift 4?

1) Swift is open source. Open source typically means that the source code behind a program, or programming language, is made available to the general public. Coders can then inspect, modify and deploy the program wherever they want.

Apple's Open Source page says: "Apple believes that using Open Source methodology makes macOS a more robust, secure operating system, as its core components have been subjected to the crucible of peer review for decades."

2) Swift is easy to learn. Apple built its language to be easy to use and with syntactic simplicity to match Python. The formatting does not require semi-colons at the end of each line, and functions are easier to understand.

3) Swift is fast. Apple claims search algorithms in Swift complete up to 2.6 times faster than Objective-C and up to 8.4 times faster than Python 2.7.

4) Swift is safe. When you work with the language, you shouldn't come across any unsafe code and modern programming conventions help keep required security in your apps.

5) Swift is familiar. If you've developed software before, you'll find Swift's syntax and concepts closely resemble those you already use.

6) Playgrounds. Swift 4 comes with a feature called Playgrounds, where Swift 4 programmers can write their code and execute it to see the results immediately. Here's How to use Swift Playgrounds.

7) Swift is the future of Apple development.

8) Swift is enterprise-ready. You can use Swift's code on Linux (Apple provides pre-built Ubuntu binaries) and Android. That's great for developers creating client/server solutions.

9) Swift is constantly improving. Swift has been in use for more than three years, and it continues to evolve with every update. We're likely to hear more developments at WWDC 2018.

Since Swift 4 has come into play, the compiled binary files size has been changed, which has resulted in the decrease of app sizes; a mobile application used to weigh 20 MB, for example, and in the newest Swift version it will take around 17MB. And there has been bug fixing, and the language has become faster.

10) Swift's memory is managed. Developers do not have to manage memory allocations: variables are initialised before use, arrays and integers are checked for overflow and memory is managed automatically. This makes the Swift programming language safer to use for developers who aren't quite as experienced.

How to get started with Swift 4

In order to develop apps for iOS, you will need a Mac and a piece of software called Xcode. Follow the steps below to get started:

  1. Open the Mac App Store on your Desktop.
  2. Search for 'Xcode' in the search bar.
  3. Click 'Get' next to the Xcode icon.

How to make apps in Swift 4: Get started

You can also find Xcode on the Mac App Store in your browser.

Online compilers: There are lots of online compilers available that will help you learn and execute Swift code, but most of them are still geared towards Swift 3. The only compiler that supports Swift 4 can be found at tutorialspoint.com.

How to write a simple App in Swift

Open Xcode, and select File > New > Project. Then choose a suitable template: in our case we will be using a Single View App.

How to make apps in Swift 4: Write a simple app

Fill in the details as required (just put your own name for Organization Name if you don't work for a company). The Organization Identifier is usually your company's URL in reverse order. Select the Language as Swift and tap Next.

Select the location where you want to create your project and you're done. Xcode will create a project for you at your desired location.

How to make apps in Swift 4: Create project

Upon creation of the project you will be presented with the following screen:

How to make apps in Swift 4: Create project 2

We will be developing an app to show the text "Hello world" on the screen along with the current date, with the background colour set to grey.

Go to the Main.storyboard file in the left pane. Drag and drop a label from the bottom-right corner on to the view and set its text to Hello World in the top-right corner.

How to make apps in Swift 4: Hello world

Now select View in the left pane and set the background colour to light grey. Run the app by clicking the play button in the top-left corner. (And make sure an appropriate choice of iPhone simulator is selected to the right of the play button: in our case it's iPhone 8 Plus.)

How to make apps in Swift 4: iPhone 8 Plus simulator

Now double-click 'viewcontroller.m'. It will open in in a separate window. Now select the Label in the storyboard by right-clicking and drag to 'viewcontroller.m' to create an outlet for the label. Outlets are used to access the controls in storyboard in our code. When the user drag and drops an outlet, it will ask for the outlet name. Enter 'label'.

Now copy and paste the following code in the viewDidLoad() method of 'viewcontroller.m'.

let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy" // setting the date format
let result = formatter.string(from: date)
self.label.text = "Hello World " + result

Your code should look like the screenshot below:

How to make apps in Swift 4: Hello world 2

When you tap the run (play) button the app builds, the simulator is launched and our app is installed on the simulator, after which the app opens and it shows us the screen below with "Hello World!" and the current date. We have successfully created our first iOS app using Swift! 

(If the text inside the label crops, increase the width of the label by dragging the edges.)

How to make apps in Swift 4: iPhone 8 Plus simulator

More advanced Swift 4 methods

We've made a simple app. Now let's move on to some methods and code snippets you can use in your own app projects.

Printing 'Hello World' in Swift

print("Hello, world!")

Defining Variables

Use 'let' to make a constant and 'var' to define a variable. The value of a constant cannot be changed once assigned; the value of a variable will change. User don't always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type.

let constVar = 42
var numberVar = 27

User can also specify the type:

var numberVar: Int = 27

Comments in Swift

Comments in Swift can be of two types.

Single line:

//This is a comment

Multiple-line comments:

/* This is a
Multiline comment */

Decision making in Swift

The syntax of an if statement in Swift 4 is as follows:

if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
}

For example:

How to make an app in Swift 4: Boolean if statement

The syntax of an if...else statement in Swift 4 is as follows:

if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

For example:

How to make apps in Swift 4: Boolean if else statement

The syntax of an if...else if...else statement in Swift 4 is as follows:

if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
   /* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
   /* Executes when the boolean expression 3 is true */
} else {
   /* Executes when the none of the above condition is true */
}

For example:

How to make apps in Swift 4: If else if else statement

Switch statement

Following is generic syntax of a switch statement in Swift 4. Here if fallthrough is used then it will continue with the execution of the next case and then come out of the Switch statement.

Switch expression {
   case expression1 :
      statement(s)
      fallthrough /* optional */
   case expression2, expression3 :
      statement(s)
      fallthrough /* optional */
   default : /* Optional */
      statement(s);
}

For example:

How to make apps in Swift 4: Switch statement

Arrays

Create arrays and dictionaries using square brackets, and access their elements by writing the index or key inside the brackets. The following line creates an array.

var arrayList = ["Apple", "Mango", "Banana", "Grapes"]

To access and modify the second element of an array we can directly write:

arrayList[1] = "Watermelon"

To create an empty array, use the initialiser syntax.

var emptyArray = [String]()
emptyArray = []

Dictionaries

var occupations = ["Steve": "Captain", "Kate": "Mechanic",]

To access and modify any value for a dictionary we can directly write:

occupations["Steve"] = "Engineer"

To create an empty dictionary, use the initialiser syntax.

occupations = [:]

Sets

Sets in Swift are similar to array but they only contain unique values.

ar a : Set = [1,2,3,4,5,6,7,8,9,0]

Swift also introduces the Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn't a value at all". You can define an Optional with '?' or '!'

var myString: String?

'?' means the value can be present or absent.

'!' means the value can be nil initially, but in future it has to have a value, or it will throw a compiler error.

No sign means the variable is not optional and it has to be assigned a value, or it will throw a compiler error.

Functions

Following is the syntax to create a function in Swift: the inputNum is the parameter name followed by the DataType, 'createStr' is the name of the function. '-> String' denotes the return type. The function takes Integer as input and converts it into String and returns it.

func createStr(Number inputNum : Int) -> String
{
    return "\(inputNum)"
}

The function can be called using the below syntax:

createStr(Number: 345)

Classes

Following is the syntax to create a Class Car. It has an optional member variable numOfPersons and a function displayDetails()

class Car
{
    var numOfPersons : Int?
    func displayDetails() {
    }
}

The class instance can be created using the line below:

var myCar : Car = Car()

The 'numOfPersons' variable can be initialised as below:

myCar.numOfPersons = 5

Closures in Swift

Closures are anonymous functions organised as blocks and called anywhere like C and Objective-C languages. Closures can be assigned to variables. Following is the syntax of a closure in Swift.

{
   (parameters) −> return type in
   statements
}

Below is a simple example. Here we are assigning a closure to the variable scname. Then on the next line we are calling the closure by calling the variable name.

How to make apps in Swift 4: Closures

Here's another example of closure which takes two variables as input and divides them.

How to make apps & games in Swift 4: Division

Extensions

In Swift we can extend the functionality of an existing class, structure or enumeration type with the help of extensions. Type functionality can be added with extensions but overriding the functionality is not possible this way.

In the below example we have a class car and we are adding an extension to the car to add another property to it. While accessing the speed property, it can be accessed directly as if it belongs to the class.

How to make apps & games in Swift 4: Class car

Tuples

The tuple type is used to group multiple values in a single compound value. Here's the syntax of Tuple declaration:

var TupleName = (Value1, value2,… any number of values) 

Here's a Tuple declaration:

var error501 = (501, "Not implemented")

Best places to learn more about Swift 4

There are a number of resources out there to help you start building apps using Swift 4. Some of the best options are listed below: 

Apple Documentation: The best place to learn Swift 4 is Apple's official documentation for Swift.

eBook: Apple has released an up-to-date eBook which is extremely useful when learning Swift 4: The Swift Programming Language (Swift 4.0.3).

Udemy: The biggest online learning resource has several courses on iOS development with Swift 4. I have listed a couple of the best ones below:

Swift Programming in Easy Steps: This book, by the author of this article, will teach you how to build iOS apps from scratch and it's fully illustrated too. You can get a copy here.

We've got more resources in a separate article: How to learn Swift 4.