Book Image

Mastering Swift 3 - Linux

By : Jon Hoffman
Book Image

Mastering Swift 3 - Linux

By: Jon Hoffman

Overview of this book

Swift is a modern, fast, and safe programming language created by Apple. Writing Swift is interactive and fun, the syntax is concise yet expressive, and the code runs lightning-fast. Swift’s move to open source has been embraced with open arms and has seen increased adoption in the Linux platform. Our book will introduce you to the Swift language, further delving into all the key concepts you need to create applications for desktop, server, and embedded Linux platforms. We will teach you the best practices to design an application with Swift 3 via design patterns and Protocol-Oriented Programming. Further on, you will learn how to catch and respond to errors within your application. When you have gained a strong knowledge of using Swift in Linux, we’ll show you how to build IoT and robotic projects using Swift on single board computers. By the end of the book, you will have a solid understanding of the Swift Language with Linux and will be able to create your own applications with ease.
Table of Contents (24 chapters)
Mastering Swift 3 - Linux
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
Learning About Variables, Constants, Strings, and Operators

What is Swift?


Swift is Apple's new programming language that was introduced at the Worldwide Developers Conference (WWDC) in 2014, alongside the integrated development environment Xcode 6 and iOS 8. Swift was arguably the most significant announcement at WWDC 2014, and very few people, including Apple insiders, were aware of the project's existence prior to it being announced. In this initial release of Swift it could only be used to develop applications for the Apple platforms.

It was amazing, even by Apple's standards, that they were able to keep Swift a secret for as long as they did, and no one suspected that they were going to announce a new development language. At WWDC 2015, Apple made another big splash when they announced Xcode 7 and Swift 2. Swift 2 was a major enhancement to the language. During that conference, Chris Lattner said that a lot of enhancements were based directly on feedback that Apple received from the development community. It was also announced at WWDC 2015 that Apple would be releasing Swift as open source, and they would be offering a port for Linux.

In December 2015, Apple officially released Swift as an open source project with the swift.org site dedicated to the open source Swift community. The Swift repository is located on Apple's github page (http://github.com/apple). The Swift evolution repository (https://github.com/apple/swift-evolution) tracks the evolution of the Swift language by documenting all of the proposed changes. You can also find a list of proposals that were accepted and rejected in this repository. If you are interested in understanding where Swift is heading, then you should check out this repository. It is interesting to note that Swift 3 contains several enhancements that were proposed by the community.

Swift 3 is a major enhancement to the language and is NOT source-compatible with previous releases. It contains fundamental changes to the language itself and to the Swift standard library. One of the main goals of Swift 3 is to be source-compatible across all platforms, so the code that we write for one platform will be compatible with all other platforms that Swift supports. This means that the code we develop for Mac OS will also work on Linux.

Development on Swift was started in 2010 by Chris Lattner. He implemented much of the basic language structure with only a few people being aware of its existence. It wasn't until late 2011 that other developers began to really contribute to Swift, and in July 2013, it became a major focus of the Apple Developer Tools group.

There are a lot of similarities between Swift and Objective-C. Swift adopts the readability of Objective-C's named parameters and its dynamic object model. When we refer to Swift as having a dynamic object model, we are referring to its ability to change at runtime. This includes adding new (custom) types and changing/extending the existing types.

While there are a lot of similarities between Swift and Objective-C, there are also significant differences between them as well. Swift's syntax and formatting are a lot closer to Python than Objective-C, but Apple did keep the curly braces. I know that Python people would disagree with me, and that is all right because we all have different opinions, but I like the curly braces. Swift actually makes the curly braces required for control statements such as if and while, which eliminates bugs, such as the goto fail in Apple's SSL library, which Apple patched in 2014.

Swift's features

When Apple said that Swift is Objective-C without the C, they were really only telling us half the story. Objective-C is a superset of C and provides object-oriented capabilities and a dynamic runtime to the C language. This means that, with Objective-C, Apple needed to maintain compatibility with C, which limited the enhancements it could make to the Objective-C language. As an example, Apple could not change how the switch statement functioned and still maintains the C compatibility.

Since Swift does not need to maintain the same C compatibility as Objective-C, Apple was free to add any feature/enhancement to the language. This allowed Apple to include the best features from many of today's most popular and modern languages, such as Objective-C, Python, Java, Ruby, C#, and Haskell.

The following chart shows a list of some of the most exciting enhancements that Swift includes:

Swift feature

Description

Type inference

Swift can automatically deduce the type of the variable or constant, based on the initial value.

Generics

Generics allow us to write the code only once to perform identical tasks for different types of objects.

Collection mutability

Swift does not have separate objects for mutable or nonmutable containers. Instead, you define mutability by defining the container as a constant or variable.

Closure syntax

Closures are self-contained blocks of functionality that can be passed around and used in our code.

Optionals

Optionals define a variable that might not have a value.

Switch statement

The Switch statement has been drastically improved. This is one of my favorite improvements.

Multiple return types

Functions can have multiple return types using tuples.

Operator overloading

Classes can provide their own implementation of existing operators.

Enumerations with Associated values

In Swift, we can do a lot more than just defining a group of related values with enumerations.

Before we can look at the Swift language itself, we need to download and install it. Let's look at how we can install Swift.

Installing Swift 3 for Linux

The following instructions were current when this book was written and works for both Ubuntu 15.10 and Ubuntu 16.04 LTS. The most up-to-date installation instructions can be found on the swift.org installation page: https://swift.org/getting-started/#installing-swift.

The first step in installing Swift is to install clang and configure it. The following are the commands:

sudo apt-get update
sudo apt-get install clang-3.6
sudo update-alternatives -install /usr/bin/clang clang
    /usr/bin/clang-3.6 100
sudo update-alternatives -install /usr/bin/clang++ clang++
    /usr/bin/clang++-3.6 100

If you forget to do the update-alternatives commands, you will receive an error: invalid inferred toolchain error when you try to build a package. Forgetting to run the update-alternatives commands is a very common error.

Now that we have the correct clang installed, we need to download Swift. You can download the latest version from the swift.org download page. The link for this page is: https://swift.org/download/.

Once you have downloaded Swift, you can install it in the location of your choice; however, you will want to avoid installing it off the root directory because that may overwrite the /usr directory. As a personal preference, I like to install Swift in the /opt directory. The following instructions will show how I install Swift.

Tip

Anytime you see {swift version}, substitute it for the version information of the Swift you are installing.

1. Go to the /opt directory:

cd /opt

2. Create a directory to hold this and all future Swift versions:

sudo mkdir swift

3. Change to the swift directory, and copy the downloaded swift file to this location:

cd swift
sudo cp -R ~/Downloads/swift-{swift version}.tar.gz ./

4. Gunzip and untar the swift file:

tar -zxvf  swift-{swift version}.tar.gz

5. The last command should have created a new directory that contains the Swift files. We will now want to create a symbolic link to this directory indicating that it is our current version of Swift:

sudo ln -s /opt/swift-{swift version} swift-current

6. All of the files in the swift directory are owned by the root user. If you attempt to build a Swift package with the package manager, while all of the files are owned by root, you will receive a permission denied error. The easiest way to fix this is to change the ownership of the Swift files to your user. If you want to give permission for multiple users to use Swift, you can add write permissions for all users. Instructions for both options are listed here and you only need to follow one of them:

//Change ownership of the Swift files
sudo chown -R {username}:{username} swift-{swift version}
//Alternatively change write permission
sudo chmod -R +x swift-{swift-version}

7. Now, we need to add Swift to our path. To do this you will have to edit your ~/.profile file and add the following line to it:

PATH=/opt/swift/swift-current/usr/bin:$PATH

8. You can either start a new terminal session to pick up the changes or run the following command in your current session:

. ~/.profile

To verify everything is good, run the swift -version command, which should output your new version of Swift. When a new version of Swift is released, install it to the /opt/swift directory and then change the swift-current symbolic link to point to this new version.

Swift language syntax

The Swift language uses modern concepts and syntax to create very concise and readable code. There is also a heavy emphasis on eliminating many common programming mistakes. Before we look at the Swift language itself, let's take a look at some of the basic syntax of the language.

Comments

When we write comments for Swift code, we can use the traditional double slash // for single-line comments and the /* and */ for multi-line comments. If we want to use the comments to also document our code, we need to use the triple slash ///.

When we write our code on a Linux computer, we do not have access to the Xcode IDE. However, since the code we write for Linux can be compatible with Apple's platforms it is a good habit to comment our code in such a manner that it will be recognized in the Xcode IDE.

Tip

This book is about using Swift for Linux, therefore we try to avoid any functionality that requires an Apple computer or an iPad. We do however use Playgrounds and Xcode in this section to illustrate how comments can be used for documentation on the Apple platform so we will understand why the format is important.

To document our code, we can use the following specific fields that Xcode recognizes:

  • Parameter: When we start a line with - parameter {param name}, Xcode recognizes this as the description for a parameter

  • Return: When we start a line with - return:, Xcode recognizes this as the description for the return value

  • Throws: When we start a line with - throws:, Xcode recognizes this as the description for the errors that this method may throw

This example shows both single-line and multi-line comments and how to use the comment fields:

To write good comments, I would recommend using single-line comments within a function to give quick one-line explanations of your code. We will then use multi-line comments outside functions and classes to explain what the function and types do. The preceding Playground shows a good use of comments. When we use proper code comments, as we did in the preceding screenshot, we can take advantage of the documentation feature within Xcode. If we hold down the option key and then click on the function name anywhere in our code, Xcode will display a popup with a description of the function.

The next screenshot shows what that popup looks like:

This screenshot shows the documentation feature of Xcode if we hold down the option key and then click on the myAdd() method. We can see that the documentation contains six fields. These fields are as follows:

  • Declaration: This is the function's declaration (that is, its signature)

  • Description: This is the description of the function as it appears in the comments

  • Parameters: The parameter descriptions are prefixed with the - Parameters: tag in the comment section

  • Throws: The throws description is prefixed with the - throws: tag and describes what errors are thrown by the methods

  • Returns: The return description is prefixed with the - returns: tag in the comment section

  • Declared In: This is the file that the function is declared in, so that we can easily find it

Semicolons

You may have noticed, from the code samples so far, that we are not using semicolons at the end of lines. Semicolons are optional in Swift; therefore, both lines in the following code are valid in Swift:

print("Hello from Swift") 
print("Hello from Swift"); 

For style purposes, it is strongly recommended that you do not use semicolons in your Swift code. If you are really set on using semicolons in your code, then be consistent and use them in every line of the code; however, Swift will not warn you if you forget them. I will stress again that it is recommended that you do not use semicolons in Swift.

Parentheses

In Swift, parentheses around conditional statements are optional; for example, both if statements in the following code are valid:

var x = 1 
 
if x == 1 { 
    print("x == 1") 
} 
 
if (x == 1) { 
    print("x == 1") 
} 

For style purposes, it is recommended that you do not include the parentheses in your code unless you have multiple conditional statements on the same line. For readability purposes, it is a good practice to put parentheses around the individual conditional statements that are on the same line.

Curly brackets

In Swift, unlike most other languages, curly brackets are required after conditional or loop statements. This is one of the safety features that is built into Swift. Arguably, there have been numerous security bugs that might have been prevented if the developer had used curly braces. These bugs could also have been prevented by other means, such as unit testing and code reviews, but requiring developers to use curly braces, in my opinion, is a good security standard.

The following code shows how to use curly brackets:

let x = 1 
 
//Valid 
if x == 1 { 
    print("x == 1") 
} 
 
//Not Valid 
if x == 1 
    print("x == 1") 

Assignment operators do not return a value

In most other languages, the following line of code is valid, but it is probably not what the developer meant to do:

if (x = 1) {} 

Tip

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you purchased. If you purchased this book from elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

In Swift, this statement is invalid. Using an assignment operator (=) in a conditional statement (if and while) will throw an error. This is another safety feature built into Swift. It prevents the developer from forgetting the second equal to sign (=) in a comparison statement.

Spaces are optional in conditional and assignment statements

For both conditional (if and while) and assignment (=) statements, white spaces are optional. Therefore, in the following code, both The i block and The j block code blocks are valid:

//The i block 
var i=1 
if i==1 { 
    print("HI") 
} 
 
//The j block 
var j = 1 
if j == 1 { 
    print("HI") 
} 

Tip

For style purposes, I would recommend adding the white spaces (such as The j block) for readability, but as long as you pick one style and are consistent, either style should be acceptable.