如何在 Mac 上使用 Swift 5 制作应用程序


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 5 expands upon its already impressive feature set. In this article we show how to use Swift 5, explain why you should, and outline all the new features in this version of the language.

If you just want to plunge in, jump ahead to How to get started with Swift 5. And for a broader overview, take a look at our Complete guide to Mac programming, which looks at a range of coding languages you can use in macOS.

Overview of Swift 5

Swift 5 is a programming language developed by Apple that allows developers to build apps for iOS, macOS, tvOS and watchOS.

The fifth version was released alongside Xcode 10.2 in March 2019 – we talk you through the new features in Swift 5 in a later section – but the Swift language has been going for a while: Swift 1.0 was released back in September 2014. According to Apple, Swift is up to 2.6 times faster than Objective C and up to 8.4 times faster than Python.

Why should you code in Swift 5?

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. It’s an ideal language to start with for beginners as the syntax is simple to understand. If you’ve developed software before, you’ll find Swift’s syntax and concepts closely resemble those you already use.

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.

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

5) Playgrounds. Xcode comes with a feature called playgrounds where Swift 5 programmers can write code and see the results immediately. Here’s How to use Swift Playgrounds.

6) Swift 5 is future-proof, and lets you develop for a number of different platforms: iOS, macOS, watchOS and tvOS.

7) Swift is constantly improving with every update. Swift 5 brought the long-awaited ABI stability, which means future Swift compilers will be able to compile code that was written in Swift 5 and above and migration of code to newer versions of Swift will be less painful for developers. This also means that the OS vendors will be able to embed the Swift Standard Library into the operating system and it will be compatible with all applications built with Swift 5 and newer versions.

We’re likely to hear more Swift developments at WWDC 2019.

How to get started with Swift 5

In order to develop apps for iOS, you will need a Mac (MacBook, iMac or Mac mini) and free software called Xcode (version 10.2 or higher). 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.
  4. You can also find Xcode on the Mac App Store in your browser.

How to make apps in Swift 5: Get started with Xcode

Online compilers

If you’re not planning on deploying your apps, you can always use a Swift online complier. This is a great way to learn and execute Swift code.

  • Online Swift Playground supports Swift 5 and it allows you to test out and execute code.
  • Repl.it has an online compiler that supports Swift 4.2 at the time of writing (May 2019) but an update is due soon.

How to write a simple app in Swift

Open Xcode, and select File > New > Project. Select Single View App from the template list.

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

Enter a name for your app, and the Organization name (this can be your company’s name or your own name). The Organization Identifier is usually your company URL in reverse order – for example com.mycompany.myapp.

Select Swift as the language and click Next. Finally, select the location on your Mac where you want Xcode to create the project.

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

Here, you will be developing a simple app, where the user can enter their name inside a text field and receive a simple greeting when they push a button.

To start, go to the Main.storyboard file in the left pane. You will see an empty View appear. Click the round button in the top right corner to open up the object library. Drag a Text Field, Label and button on to the View.

How to make apps in Swift 5: Text greeting

How to make apps in Swift 5 on Mac: Text field

Select the Button in the View Hierarchy and set its title to “Generate greeting” in the Utility area on the righthand side.

How to make apps in Swift 5: Generate greeting

Double-click the ViewController.swift file. It will open in in a separate window.

Now select the Text Field in the view and hold Ctrl and drag to the top of the ViewController class. You will be prompted to create an IBOutlet for the Text Field. Call it “textField”.

How to make apps in Swift 5 on Mac: ViewController

Do the same for the Label and name the IBOutlet “label”. You will also need to do the same for the Button, but instead of dragging it to the top of the ViewController, drag it to the bottom to create an IBAction method. Name the method “buttonTapped”.

IBOutlets are used to access the controls in storyboard in our code and IBAction methods are used for reacting to button events like taps.

Add the following code in the buttonTapped method of your ViewController class:

if let name = textField.text { self.label.text = “Hello ” + name}

This is how the ViewController.swift file should look like after these changes:

How to make apps with Swift 5 on Mac: ViewController file

You’re now ready to run the app. Press the run button, and the app will be launched on the simulator.

When the user adds their name in the Text Field and taps the Button, the Label at the bottom will display “Hello” along with the entered name.

How to make apps in Swift 5 on Mac: Run app

Swift 5 concepts (Basic & Advanced)

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 text 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 can change. Users 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 = 42var numberVar = 27

The developer can also specify the type. In the example below, we are declaring an integer.

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 aMultiline comment */

Decision making in Swift

The syntax of an if statement in Swift 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 5: Boolean if statement

The syntax of an if…else statement in Swift 5 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 5: Boolean if else statement

The syntax of an if…else if…else statement in Swift 5 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 a generic syntax of switch statement available in Swift 5. 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 – ie [ and ] – and access their elements by writing the index or key in brackets. The following line creates an array.

var arrayList = [“Swift”, “JavaScript”, “Java”, “PHP”]

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

arrayList[2] = “React Native”

To create an empty array, use the initialiser syntax.

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

Dictionaries

var occupations = [“Steve”: “Developer”, “Kate”: “Designer”,]

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

occupations[“Steve”] = “CTO”

To create an empty dictionary, use the initialiser syntax.

occupations = [:]

Sets

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

var 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 when it’s used it has to have a value, or it will generate a runtime error.

No sign means the variable is not optional and it has to be assigned a value, or it will generate 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

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 a Tuple declaration:

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

Here’s a Tuple declaration:

var error501 = (501, “Not implemented”)

New features in Swift 5

Let’s look at the new elements in Swift 5 in more detail.

Raw Strings

Swift 5 brings us raw strings, a feature that makes it easier to create strings that contain quote marks and backslashes without the need to use escape sequences like in previous Swift versions. In raw strings, quote marks and backslashes are interpreted literally as those symbols instead of being interpreted as string termination or escape characters.

To use raw strings, you only have to add # at the beginning and the end of the string:

How to make apps with Swift 5: Raw strings

Because the backslash in raw strings is interpreted as a literal symbol, to use string interpolation in raw strings you have to add another # after the backslash symbol:

How to make apps in Swift 5 on Mac: Hashtags

If you need to use the “# sequence together inside a raw string you need to add ## at the beginning and the end of the string:

How to make apps in Swift 5 on Mac: Raw strings with hashtags

Finding integer multiples

In Swift 4.2 and earlier versions, to find if a number is a multiple of another one, you would have to use the modulo operator (%). Now in Swift 5, there’s a dedicated method for that, which makes the code much clearer:

How to make apps in Swift 5 on Mac: Finding integer multiples

Handling future enum cases

Switch statements in Swift must always be exhaustive. This means that you always have to handle all the enum cases or handle only specific cases with the addition of the default case that handles all other cases:

How to make apps in Swift 5 on Mac: Handling future enum cases

The problem with this approach is that if in the future the developer decides to add another case to the enum, there will be no warning by the compiler that the new case was added. This means that the new case will be handled by the default case which is not always something that you want.

To address this issue, a new @unknown attribute was added in Swift 5. You use this attribute together with the default case.

How to make apps in Swift 5 on Mac: Use the unknown attribute

With the @unknown default case in the switch statement, the compiler will issue a warning if a new case was added to the enum in the future. This way, the developer can decide whether to handle the new case or not.

Flattening nested optionals

Nested optionals can be created by handling code that throws using try?. In Swift 5, the nested optional is flattened into a regular optional. This matches the behaviour of conditional type-casting and optional chaining.

How to make apps in Swift 5 on Mac: Nested optionals

In the example above, you can see that the model variable is of type String? and not String?? like it was in Swift 4.2.

Result type in the Standard Library

In Swift 5, the Result type was added to the Standard Library. The Result type gives you a clean and simple way of handling errors in asynchronous code. It is implemented as an enum with success and failure cases. Both of the cases are implemented using generics. The success case can have an associated value of any type while the failure case has to have an associated value that conforms to the Error protocol. Here is an example that demonstrates the usage of the Result type:

How to make apps in Swift 5 on Mac: Result type

In the example above, we have implemented a simple ApiClient that fetches names from a URL. Note that the second parameter in the fetchNames function is a completion closure that accepts a Result type. The Result type in our example uses [String] for the success case and ApiError for the failure case.

Now, we can use the code above like this:

How to make apps in Swift 5 on Mac: Result type 2

Other features in Swift

We looked at the new features in the latest version in Swift in an earlier version. But it’s still worth knowing about the features that survive from older versions. Here are some highlights that were added in Swift 4:

Strings

As of Swift 4, String 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 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 simplified 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 made 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 went one step further and let 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

Best places to learn more about Swift 5 programming

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

Apple Documentation: The best place to learn Swift 5 is Apple’s official documentation for Swift.

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

Udemy: The biggest online video learning service has several courses that cover various versions of Swift. Here are a few which cover Swift 5:

Swift programming in easy steps – covers iOS 12 and Swift 5: This book, by the author of this article, will teach you how to build iOS apps using Swift 5 from scratch and it’s fully illustrated too. You can get a copy from Amazon.

Hacking with Swift: A great way to learn about development with Swift is by using the books on the Hacking with Swift website. It is maintained by Paul Hudson, a great Swift developer and enthusiast.

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