Book Image

Mastering Swift 2

By : Jon Hoffman
Book Image

Mastering Swift 2

By: Jon Hoffman

Overview of this book

<p><span id="description" class="sugar_field">At their Worldwide Developer’s conference (WWDC) in 2015, Apple announced Swift 2, a major update to the innovative programming language they first unveiled to the world the year before. Swift 2 features exciting enhancements to the original iteration of Swift, acting, as Apple put it themselves as “a successor to the C and Objective-C languages.” – This book demonstrates how to get the most from these new features, and gives you the skills and knowledge you need to develop dynamic iOS and OS X applications.<br /> </span></p> <p><span id="description" class="sugar_field">Learn how to harness the newest features of Swift 2 todevelop advanced applications on a wide range of platforms with this cutting-edge development guide. Exploring and demonstrating how to tackle advanced topics such as Objective-C interoperability, ARC, closures, and concurrency, you’ll develop your Swift expertise and become even more fluent in this vital and innovative language. With examples that demonstrate how to put the concepts into practice, and design patterns and best practices, you’ll be writing better iOS and OSX applications in with a new level of sophistication and control.</span></p>
Table of Contents (24 chapters)
Mastering Swift 2
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Free Chapter
1
Taking the First Steps with Swift
2
Learning about Variables, Constants, Strings, and Operators
Index

Playgrounds


When I was a kid, the best part of the school day was going to the playground. It really did not matter what we were playing; as long as we were on the playground, I knew it would be fun. When Apple introduced Playgrounds as part of Xcode 6, I was excited just by the name, but I wondered if Apple could make its Playground as fun as the playgrounds from my youth. While Apple's Playgrounds might not be as fun as playing kickball when I was 9 years old, it definitely brings a lot of fun back to experimenting and playing with code.

Getting started with Playgrounds

Playgrounds are interactive work environments that let us write code and see the results immediately. As changes are made to the code, the results also change in real time. This means that Playgrounds are a great way to learn and experiment with Swift.

Playgrounds also make it incredibly easy to try out the new APIs, prototype new algorithms, and demonstrate how code works. We will be using Playgrounds throughout this book to show how our sample code works. Therefore, before we really get into Swift development, let's spend some time learning about and getting comfortable with Playgrounds.

Do not worry if the Swift code does not make a lot of sense right now, as we go through the book, this code will begin to make sense. We are simply trying to get a feel of Playgrounds right now.

A Playground can have several sections, but the three that we will be using in this book are:

  • Coding Area: This is where you enter your Swift code.

  • Results Sidebar: This is where the results of your code are shown. Each time you type in a new line of code, the results are re-evaluated and the results' sidebar is updated with the new results.

  • Debug Area: This area displays the output of the code, and it can be very useful for debugging.

The following screenshot shows how the sections are arranged in a Playground:

Let's start a new Playground. The first thing we need to do is to start Xcode. Once Xcode has started, we can select the Get started with a playground option, as shown in the following screenshot:

Alternatively, we can navigate to the Playground by going to File | New from the top menu bar, as shown in the following screenshot:

Next, we should see a screen similar to the following screenshot that lets us name our Playground and select whether the Playground is an iOS or OS X Playground.

For most of the examples in this book, it is safe to assume that you can select either iOS or OS X unless it is otherwise noted:

Finally, we are asked for the location to save our Playground. After we select the location, the Playground will open up and look similar to the following screenshot:

In the preceding screenshot, we can see that the coding area of the Playground looks similar to the coding area for an Xcode project. What is different here is the sidebar on the right-hand side. This sidebar is where the results of our code are shown. The code in the previous screenshot imports iOS' UIKit framework and sets a variable named str to the string, Hello, playground. You can see the content of the str string in the sidebar to the right of the code.

By default, a new Playground does not open the debug area. You can open it manually by pressing the shift + command + Y keys together. Later in the chapter, we will see why the debug area is so useful.

iOS and OS X Playgrounds

When you start a new iOS Playground, the Playground imports UIKit (Cocoa Touch). This gives us access to the UIKit framework that provides the core infrastructure for iOS applications. When we start a new OS X Playground, the Playground imports Cocoa. This gives us access to the OS X Cocoa framework.

What the last paragraph means is if we want to experiment with the specific features of either UIKit or Cocoa, we will need to open the correct Playground. As an example, if we have an iOS Playground open and we want to create an object that represents a color, we would use a UIColor object. If we had an OS X playground open, we would use an NSColor object to represent a color.

Showing images in a Playground

As you will see throughout this book, Playgrounds are great at showing the results of code as text in the results sidebar. However, they can also do a lot more than just text, such as images, graphs, and display views. Let's take a look at how we would show an image in a Playground. The first thing we need to do is to load the image into the resource directory of our Playground.

The following steps show how to load an image into the resource directory:

  1. Let's begin by showing the project navigator sidebar. To do this, in the top menu bar, navigate to View | Navigators | Show Project Navigator or use the command + 1 keyboard shortcut. The project navigator looks similar to this:

  2. Once we have the Project Navigator open, we can drag the image into the Resources folder so that we can access it from our code. Once we drag the image file over it and drop it, it will appear in the Resources folder, as shown here:

  3. Now, we can access the image that is in our Resources folder within our code. The following screenshot shows how we would do this. The actual code that we use to access the image is not as important at this time as knowing how to access resources within a playground:

  4. To view the image, we need to hover our cursor in the results sidebar over the section that shows the width and height of the image. In our example, the width and height section shows w 256 h 256. Once we hover the mouse pointer over the width and height, we should see two symbols, as shown in the following screenshot:

  5. We can press either of the symbols to show the image. The one that is shaped like a circle with a plus sign in it will display the image within the playground's code section, while the one that looks like an eye will pop the image up outside the playground. The following screenshot shows what it shows if we press the circle with a plus sign in it:

Having the ability to create and display graphs can be very useful when we want to see the progression of our code. Let's look at how we can create and display graphs in a playground.

Creating and displaying graphs in Playgrounds

We can also graph the value of numeric variables over time. This feature is really useful when we are prototyping new algorithms because it allows us to see the value of the variable throughout the course of the calculations.

To see how graphing works, take a look at the following Playground:

In this playground, we set the variable j to 1. Next, we create a for loop that assigns numbers 1 through 5 to the variable i. At each step in the for loop, we set the value of the variable j to the current value of j multiplied by i. The graph shows the values of the variable j at each step of the for loop. We will be covering for loops in detail later in this book.

To bring up the graph, click on the symbol that is shaped like a circle with a dot in it. We can then move the timeline slider to see the values of variable j at each step of the for loop.

What Playgrounds are not

There is a lot more that we can do with Playgrounds, and we have only scratched the surface in our quick introduction here. As we proceed through the book, we will be using Playgrounds for almost all of the sample code and demonstrate other features of Playgrounds as they are used.

Before we leave this brief introduction, let's take a look at what Playgrounds are not so that we can understand when not to use Playgrounds:

  • Playgrounds should not be used for performance testing: The performance you see from any code that is run in a Playground is not representative of how fast the code will run when it is in your projects

  • Playgrounds do not support user interaction: Users cannot interact with code that is run in a Playground

  • Playgrounds do not support on-device execution: You cannot run the code that is present in a Playground as an external application or on an external device

Swift language syntax

If you are an Objective-C developer, and you are not familiar with modern languages such as Python or Ruby, the code in the previous screenshots may have looked pretty strange. The Swift language syntax is a huge departure from Objective-C, which was based largely on Smalltalk and C.

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

Comments

Writing comments in Swift code is a little different from writing comments in Objective-C code. We still use the double slash // for single line comments and the /* and */ for multiline comments.

What has changed is how we document the parameters and the return value. To document any parameter, we use the :parm: field, and for the return value, we use the :return: field.

The following Playground shows examples of both single line and multiline comments to properly comment a function:

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 the multiline comments outside of functions and classes to explain what the function and class does. The preceding Playground shows a good use of comments. By using proper documentation, as we did in the preceding screenshot, we can use 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 the description of the function.

This next screenshot shows what that popup would look similar to:

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 five fields. These fields are:

  • Declaration: This is the function's declaration

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

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

  • Returns: The return description is prefixed with the :return: 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 probably noticed, from the code samples so far, that we are not using semicolons at the end of lines. The semicolons are optional in Swift; therefore, both lines in the following Playground are valid in Swift. You can see the results of the code in the results sidebar, as shown in the following screenshot:

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 on every line of 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 Playground are valid. You can see the results of the code in the sidebar, as shown in the following screenshot:

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 good practice to put parentheses around the individual conditional statements that are on the same line.

See the following Playground for samples:

Curly braces

In Swift, unlike most other languages, the curly bracket is required after statements. This is one of the safety features that are built into Swift. Arguably, there have been numerous security bugs that may have been prevented if the developer would have used curly braces. A good example of this is Apple's goto fail bug. 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 Playground shows you what error you get if you forget to include the curly braces:

An assignment operator does not return a value

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

if (x = 1) {}

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book 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 not valid. 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 equals sign (=) in a comparison statement. This error is shown in the following Playground:

Spaces are optional in conditional and assignment statements

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

Note

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