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

The need for optional types in Swift


Now, the burning question is why does Swift need optionals? To understand this question, we should examine what problems optionals are designed to solve.

In most languages, it is possible to create a variable without giving it an initialized value. For example, in Objective-C, both of these lines of code are valid:

int i; 
MyObject *m; 

Now, let's say that the MyObject class has the following method:

-(int)myMethodWithValue:(int)i { 
    return i*2; 
} 

This method takes the value passed in from the i parameter, multiplies it by 2, and returns the results. Let's try to call this method using the following code:

MyObject *m; 
NSLog(@"Value: %d",[m myMethodWithValue:5]); 

Our first thought might be that this code would display Value: 10, since we are passing the value of 5 to a method that doubles the value passed in; however, this would be incorrect. In reality, this code would display Value: 0 because we did not initialize...