Introducing the Swift Programming Language

In this article by Steven Daniel, the author of Apple Watch App Development, we will introduce ourselves to Apple's Swift programming language. At WWDC 2014, Apple introduced a brand new programming language called Swift. The Swift programming language brings concise syntax, type safety, and modern programming language features to Mac and iOS developers.

(For more resources related to this topic, see here.)

Since its release, the Apple developer community has responded with great excitement, and developers are rapidly starting to adopt this new language within their own applications. The Swift language is the future of developing on Apple's platforms.

This article includes the following topics:

  • Learning how to register as an Apple developer
  • Learning how to download and install Xcode development tools
  • Introduction to the Swift programming language
  • Learning how to work with Xcode playgrounds
  • Introduction to the newest additions in Swift 2.0

Registering as an Apple developer

Before you can begin building iOS applications for your iOS devices, you must first join as a registered user of Apple Developer Program in order to download all of the necessary components to your computer. The registration process is free and provides you with access to the iOS SDK and other developer resources that are really useful to get you started.

The following short list outlines some of the things that you will be able to access once you become a registered member of Apple Developer Program:

  • It provides helpful “Getting Started” guides to help you get up and running quickly
  • It gives you helpful tips that show you how to submit your apps to App Store
  • It provides the ability to download the current releases of iOS software
  • It provides the ability to beta test the releases of iOS and the iOS SDK
  • It provides access to Apple Developer Forums

Whether you develop applications for the iPhone or iPad, these use the same OS and iOS SDK that allows you to create universal apps that will work with each of these devices. On the other hand, Apple Watch uses an entirely different OS called watchOS.

To prepare your computer for iOS development, you need to register as an Apple developer. This free process gives you access to the basic levels of development that allow you to test your app using iOS Simulator without the ability to sell your app on Apple App Store. The steps are as follows:

  1. To sign up to Apple Developer Program, you will need to go to https://developer.apple.com/programs/ and then click on the Enroll button to proceed, as shown in the following screenshot:
  2. Next, click on the Start Your Enrollment button, as shown in the following screenshot:
  3. Once you sign up, you will then be able to download the iOS SDK and proceed with installing it onto your computer.

You will then become an official member of Apple Developer Program. You will then be able to download beta software so that you can test them on your actual device hardware as well as having the freedom to distribute your apps to your end users.

In the next section, we will look at how to download and install Xcode development tools.

Getting and installing Xcode development tools

In this section, we will take a look at what Integrated Development Environments (IDEs) and Software Development Kits (SDKs) are needed to develop applications for the iOS platform, which is Apple's operating system for mobile devices. We will explain the importance of each tool's role in the development cycle and the tools required to develop applications for the iOS platform, which are as follows:

  • An Intel-based Mac computer running OS X Yosemite (10.10.2) or later with the latest point release and security patches installed is required. This is so that you can install the latest version of the Xcode development tool.
  • Xcode 6.4 or later is required. Xcode is the main development tool for iOS. You need Xcode 6.4 minimum as this version includes Swift 1.2, and you must be registered as an Apple developer. The iOS SDK consists of the following components:

Component

Description

Xcode

This is the main IDE that enables you to develop, edit, and debug your native applications for the iOS and Mac platforms using the Objective-C or Swift programming languages.

iOS Simulator

This is a Cocoa-based application that enables you to debug your iOS applications on your computer without the need of having an iOS device. There are many iOS features that simply won't work within Simulator, so a device is required if an application uses features such as the Core Location and MapKit frameworks.

Instruments

These are the analysis tools that help you optimize your applications and monitor memory leaks during the execution of your application in real time.

Dashcode

This enables you to develop web-based iOS applications and dashboard widgets.

Once you are registered, you will need to download and install Xcode developer tools by performing the following steps:

  1. Begin by downloading and installing Xcode from Mac App Store at https://itunes.apple.com/au/app/xcode/id497799835?mt=12.
  2. Select either the Free or Install button on the App Store page. Once it completes the installation process, you will be able to launch Xcode.app from your Applications folder.

You can find additional development tools from the Apple developer website at https://developer.apple.com/.

In the next section, we will be look at what exactly Xcode playgrounds are and how you can use them to experiment with designing code algorithms prior to incorporating the code into your project. So, let's get started.

Introduction to Xcode playgrounds

A playground is basically an interactive Swift coding environment that displays the results of each statement as updates are made without having the need to compile and run a project. You can use playgrounds to learn and explore Swift, prototype parts of your app, and create learning environments for others. The interactive Swift code environment lets you experiment with algorithms, explore system APIs, and even create your very own custom views without the need of having to create a project. Once you perfect your code in the playground, simply move this code into your project. Given that playgrounds are highly interactive, they are a wonderful vehicle for distributing code samples with instructive documentation and can even be used as an alternative medium for presentations.

With the new Xcode 7 IDE, you can incorporate rich text comments with bold, italic, and bulleted lists with the addition of having the ability to embed images and links. You can even embed resources and support Swift source code in the playground to make the experience incredibly powerful and engaging, while the visible code remains simple.

Playgrounds provide you with the ability to do the following:

  • Share curriculum to teach programming with beautiful text and interactive code
  • Design a new algorithm and watch its results every step of the way
  • Create new tests and verify that they work before promoting them into your test suite
  • Experiment with new APIs to hone your Swift coding skills
  • Turn your experiments into documentation with example code that runs directly within the playground

Let's begin by opening the Xcode IDE and explore how to create a new playground file for the first time. Perform the following steps:

  1. Open the Xcode.app application either using the finder in your Applications directory or using Apple's Launchpad. If you've never created or opened an Xcode project before, you will be presented with the following screen:
  2. In the Welcome to Xcode dialog, select the Get started with a playground option. If this dialog doesn't appear, you can navigate to File | New | Playground… or simply press Shift + Option + Command + N.
  3. Next, enter SwiftLanguageBasics as the name of your playground.
  4. Then, ensure that you choose iOS as the platform that we will target.
  5. Click on the Next button to proceed to the next step in the wizard.
  6. Specify the location where you would like to save your project.
  7. Then, click on the Create button to save your playground at the specified location.

Once your project is created, you will be presented with the default playground template, as shown in the following screenshot:

In the next section, you will begin learning about some of the Swift language basics, start adding lines of code within this playground file, and see the results that we get when they are executed.

Introduction to the Swift language

In this section, we will introduce some of the new and exciting features of the Swift programming language. So, let's get started.

Variables, constants, strings, and semicolons

Our next step is to familiarize ourselves with the differences between variables, constants, strings, and semicolons in a bit more detail. We will work with and use Xcode playgrounds to put each of these into practice.

Variables

A variable is a value that can change. Every variable contains a name, called the variable name, and must contain a data type. The data type indicates what sort of value the variable represents, such as whether it is an integer, a floating point number, or a string.

Let's take a look at how we can put this into practice and create a variable in Swift.

First, let's start by revealing the console output window by navigating to View | Debug Area | Show Debug Area.

Next, clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Variables
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

var myGreeting = "Welcome to Learning the basics of Swift Programming"
print(myGreeting, terminator: "")

As you begin to type in the code, you should immediately see the Welcome to Learning the basics of Swift text magically appear in the right-hand pane in which the assignment takes place and it appears once more for the print statement.

The right-hand pane is great to show you smaller output, but for longer debugging output, you would normally take a look at the Xcode console.

Constants

A constant is basically a value that cannot be changed. Creating these constant variables prevents you from performing accidental assignments and can even improve performance.

Let's take a look at how we can put this into practice and create a constant variable in Swift.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Constants
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

let myGreeting = "Welcome to Learning the basics"
print(myGreeting, terminator: "")

myGreeting += " of Swift Programming"

Take a look at the screenshot now:

As you begin to type in the code, you will immediately receive an error message stating that you cannot assign myGreeting to our let value because the object is not mutable. In Swift, you can control the mutability of the built-in Swift types by using either the let or var keywords during declaration.

Strings

A string is basically an ordered collection of characters—for example "hello, world". In Swift, strings are represented by the String data type, which represents a collection of values of the char data type.

You can use strings to insert constants, variables, literals, and expressions into longer strings in a process known as string interpolation, which we will cover later on in this article. This makes it easy to create custom string values for display, storage, and printing.

Let's take a look at how we can put this into practice, create a String variable in Swift, and utilize some of the string methods.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Strings
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

let myGreeting = "Welcome to Swift Language Basics, working with Strings"

// Make our String uppercase
print(myGreeting.uppercaseString)

// Append exclamation mark at the end of the string
var newGreeting = myGreeting.stringByAppendingString("!!!")
print(newGreeting)

Take a look at the screenshot now:

As you can note in the preceding code snippet, we began by importing the Foundation framework class, which contains several APIs to deal with objects such as strings and dates. Next, we declared our myGreeting constant variable and then assigned a default string. We then used the uppercaseString method of the string object to perform a function to make all of the characters within our string uppercase. In our next step, we will declare a new variable called newGreeting and call the stringByAppendingString method to append additional characters at the end of our string.

For more information on using the String class, you can consult the Swift programming language documentation at https://developer.apple.com/library/ios/documentation/Swift/Conceptual/S....

Semicolons

As you would have probably noticed so far, the code you wrote doesn't contain any semicolons. This is because in Swift, these are only required if you want to write multiple statements on a single line.

Let's take a look at a code example to see how we can put this into practice.

Delete the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Semicolons
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

var myGreeting = "Welcome to Swift Language"
let newString = myGreeting + " Basics, ".uppercaseString + "working with semicolons"; print(newString)

Take a look the following screenshot now:

As you can note in the preceding code snippet, we began by declaring our myGreeting variable and then assigned a default string. In our next step, we declared a new variable called newString, concatenated the details from our myGreeting string, and used the uppercaseString method, which cycles through each character within our string, making our characters uppercase.

Next, we appended the additional working with semicolons string to the end of our string and finally used the print statement to output the contents of our newString variable to the console window. As you must have noticed, we included a semicolon to the end of the statement; this is because in Swift, you are required to include semicolons if you want to write multiple statements on a single line.

Numeric types and conversion

In this section, we will take a look at how we can perform arithmetic operations on our Swift variables. In this example, we will look at how to calculate the area of a triangle, given a base and height value.

Let's take a look at a code example to see how we can put this into practice.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics - Numeric Types and Conversion
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// method to calculate the area of a triangle
func calcTriangleArea(triBase: Double, triHeight: Double) -> Double {
    return (triBase * triHeight) / 2
}

// Declare our base and height of our triangle
let base = 20.0
let height = 120.0

// Calculate and display the area of the triangle and
print ("The calculated Area is: " + String(calcTriangleArea(base, triHeight: height)));

Take a look at the following screenshot now:

As you can note in the preceding code snippet, we started by creating our calcTriangleArea function method, which accepts a base and a height parameter value in order to calculate the area of the triangle. In our next step, we declared two variables, base and height, which contain the assigned values that will be used to calculate the base and the height of our triangle. Next, we made a call to our calcTriangleArea method, passing in the values for our base and height before finally using the print statement to output the calculated area of our triangle to the console window.

An important feature of the Swift programming language is that all numeric data type conversions must be explicit, regardless of whether you want to convert to a data type containing more of less precision.

Booleans, tuples, and string interpolation

In this section, we will look at the various features that come with the Swift programming language. We will look at the improvements that Swift has over Objective-C when it comes to using Booleans and string interpolation before finally discussing how we can use tuples to access elements from a string.

Booleans

Boolean variables in Swift are basically defined using the Bool data type. This data type can only hold values containing either true or false.

Let's take a look at a code example to see how we can put this into practice.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Booleans
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

let displaySettings : Bool = true
print("Display Settings is: " + (displaySettings ? "ON" : "OFF"))

Take a look at the following screenshot now:

As you can note from the preceding code snippet, we started by declaring our constant variable called displaySettings and assigned it a default Boolean value of true. Next, we performed a check to see whether the value of our displaySettings variable is set to true and called our print statement to output the Display Settings is: ON value to the console window.

In Objective-C, you would assign a value of 1 and 0 to denote true and false; this is no longer the case with Swift because Swift doesn't treat 1 as true and 0 as false. You need to explicitly use the actual Boolean values to stay within Swift's data type system.

Let's replace the existing playground code with the following code snippet to take a look at what would happen if we changed our value from true to 1:

 /*:
# Swift Language Basics – Booleans
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

let displaySettings : Bool = 1 // This will cause an error!!!
print("Display Settings is: " + (displaySettings ? "ON" : "OFF"))

Take a look at the following screenshot now:

As you can note from the previous screenshot, Swift detected that we were assigning an integer value to our Boolean data type and threw an error message.

Tuples

Tuples provide you with the ability to group multiple values into a single compound value. The values contained within a tuple can be any data type, and therefore are not required to be of the same type.

Let's take a look at a code example, to see how we can put this into practice.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics – Tuples
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// Define our Address Details
var addressDetails = ("Apple Inc.", "1 Infinite Loop", "Cupertino, California", "United States");

print(addressDetails.0) // Get the Name
print(addressDetails.1) // Address
print(addressDetails.2) // State
print(addressDetails.3) // Country

Take a look at the following screenshot now:

As you can note from the preceding code snippet, we started by declaring a tuple variable called addressDetails that contains a combination of strings. Next, we accessed each of the tuple elements by referencing their index values and displayed each of these elements in the console window.

Let's say that you want to modify the contents of the first element within your tuple. Add the following code snippet after your var addressDetails variable:

// Modify the element within our String
addressDetails.0 = "Apple Computers, Inc."

Take a look at the following screenshot now:

As you can note from the preceding screenshot, we modified our first component within our tuple to the Apple Computers, Inc value. If you do not want modifications to be made to your variable, you can just change the var keyword to let, and the assignment would result in a compilation error.

You can also express your tuples by referencing them using their named elements. This makes it really useful as you can ensure that your users know exactly what the element refers to. If you express your tuples using their named elements, you will still be able to access your elements using their index notation, as can be seen in the following highlighted code snippet:

/*:
# Swift Language Basics – Tuples
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// Define our Address Details
var addressDetails = (company:"Apple Inc.", Address:"1 Infinite Loop", City:"Cupertino, California", Country:"United States");

// Accessing our Tuple by using their NAMES

print("Accessing our Tuple using their NAMES\n")
print(addressDetails.company) // Get the Name
print(addressDetails.Address) // Address
print(addressDetails.City)    // State
print(addressDetails.Country) // Country

// Accessing our Tuple by using their index notation

print("\nAccess our Tuple using their index notation:\n")
print(addressDetails.0) // Get the Name
print(addressDetails.1) // Address
print(addressDetails.2) // State
print(addressDetails.3) // Country

Take a look at the following screenshot now:

As you can note from what we covered so far about tuples, these are really cool and are basically just like any other data type in Swift; they can be really powerful to use within your own programs.

String interpolation

String interpolation means embedding constants, variables, as well as expressions within your string literals. In this section, we will take a look at an example of how you can use this.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics - String Interpolation
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// Define our Address Details
var addressDetails = (company:"Apple Inc.", Address:"1 Infinite Loop", City:"Cupertino, California", Country:"United States");

// Use String Interpolation to format output
print("Apple Headquarters are located at: \n\n" + addressDetails.company + ",\n"
    + addressDetails.Address + "\n" + addressDetails.City + "\n"
    + addressDetails.Country);

Take a look at the following screenshot now:

As you can note from the preceding code snippet, we started by declaring a tuple variable called addressDetails that contains a combination of strings. Next, we performed a string concatenation to generate our output in the format that we want by accessing each of the tuple elements using their index values and displaying each of these elements in the console window.

Let's take this a step further and use string interpolation to place our address detail information into string variables. The result will still be the same, but I just want to show you the power of using tuples with the Swift programming language.

Clear the contents of the playground template and replace them with the following highlighted code snippet:

/*:
# Swift Language Basics - String Interpolation
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// Use String Interpolation to place elements into string initializers
var addressDetails = ("Apple Inc.", "1 Infinite Loop", "Cupertino, California", "United States");
let (Company, Address, City, Country) = addressDetails

print("Apple Headquarters are located at: \n\n" + Company + ",\n" + Address + "\n" + City + "\n" + Country);

Take a look at the following screenshot now:

As you can note from the preceding code snippet, we removed the named types from our addressDetails string contents, created a new type using the let keyword, and assigned placeholders for each of our tuple elements. This is very handy as it not only makes your code a lot more readable but you can also continue to create additional placeholders for the additional fields that you create.

Controlling the flow

In this section, we will take a look at how to use the for…in loop to iterate over a set of statements within the body of the loop until a specific condition is met.

The for…in loops

The for…in loops basically perform a set of statements over a certain number of times until a specific condition is met, which is typically handled by incrementing a counter each time until the loop ends.

Let's take a look at a code example to see how we can put this into practice.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics - Control Flow
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

// Perform a fibonacci loop using the For-In Loop
var fibonacci = 0
var iTemp = 1
var jTemp = 0

for iterator in 0...19 {
    jTemp = fibonacci
    fibonacci += iTemp
    iTemp = jTemp
    print("Fibonacci: " + String(fibonacci), terminator: "\n")
}

Take a look at the following screenshot now:

The preceding code demonstrates the for…in loop and the closed range operator (...). These are often used together, but they are entirely independent.

As you can note from the preceding code snippet, we declared the exact same variables: fibonacci, iTemp, and jTemp. Next, we used the for…in loop to iterate over our range, which is from 0 to 19, while displaying the current Fibonacci value in the console window.

What's new in Swift 2.0

In this section, we will take a look at some of the new features that come as part of the Swift 2.0 programming language.

Error handling

Error handling is defined as the process of responding to and recovering from error conditions within your program. The Swift language provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. In Swift, these are referred to as throwing functions and throwing methods.

In Swift 2.0, error handling has vastly improved and adds an additional layer of safety to error checking. You can use the throws keyword to specify which functions and method are most likely to cause an error. You can implement and use the do, try, and catch keywords to handle something that could likely throw an error.

Let's take a look at a code example to see how we can put this into practice.

Clear the contents of the playground template and replace them with the following code snippet:

/*:
# Swift Language Basics - What's new in Swift 2.0
: Created by Steven F. Daniel
: Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved.
*/

import Foundation

enum EncryptionError: ErrorType {
    case Empty
    case Short
}
// Method to handle the Encryption
func encryptString(str: String, withPassword password: String) throws -> String {
    if password.characters.count > 0 {
        // Password is valid
    } else { throw EncryptionError.Empty }

    if password.characters.count >= 5 {
        // Password is valid
    } else { throw EncryptionError.Short }

    // Begin constructing our encrypted string
    let encrypted = password + str + password
    return String(encrypted.characters.reverse())
}

// Call our method to encrypt our string
do {
    let encrypted = try encryptString("Encrypted String Goes Here", withPassword: "123")
    print(encrypted)
} catch EncryptionError.Empty {
    print("You must provide a password.")
} catch EncryptionError.Short {
    print("Passwords must be at least five characters.")
} catch {
    print("An error occurred!")
}

Take a look at the following screenshot now:

As you can note in the preceding code, we began by creating an enum object that derives from the ErrorType class so that we could create and throw an error. Next, we created a method called encryptString that takes two parameters: str and password. This method performed a check to ensure that we didn't pass an empty password.

If our method determines that we did not specify a valid password, we will automatically throw an error using EncryptionError.Empty and exit from this method. Alternatively, if we provide a valid password and string to encrypt, our string will be encrypted.

Binding

Binding in Swift is something new and provides a means of checking whether a variable contains a valid value prior to continuing and exiting from the method otherwise. Fortunately, Swift 2.0 provides you with exactly this, and it is called the guard keyword.

Let's go back to our previous code snippet and take a look at how we can implement the guard statement to our conditional checking within our encryptedString method.

Modify the contents of the playground template and replace them with the following highlighted sections:

// Method to handle the Encryption
func encryptString(str: String, withPassword password: String) throws -> String {

    guard password.characters.count > 0  else { throw 
    EncryptionError.Empty }
    guard password.characters.count >= 5 else { throw 
    EncryptionError.Short }

    // Begin constructing our encrypted string
    let encrypted = password + str + password
    return String(encrypted.characters.reverse())
}

As you can note in the preceding code snippet, using the guard keyword, you can provide a code block to perform a conditional check within the else statement that will run if the condition fails. This will make your code cleaner as the guard statement lets you trap invalid parameters from being passed to a method. Any conditions you would have checked using if before you can now check using guard.

Protocol extensions

In Swift 2.0, you have the ability to extend protocols and add additional implementations for properties and methods. For example, you can choose to add additional methods to the String or Array classes, as follows:

/*
# What's new in Swift 2.0 - Protocol Extensions
The first content line displayed in this block of rich text.
*/

import Foundation

let greeting = "Working with Swift Rocks!"

// Extend the String class to include additional methods
extension CustomStringConvertible {
    var uCaseString: String {
       return "\(self.description.uppercaseString)!!!"
    }
}
print(greeting.uCaseString)

Take a look at the following screenshot now:

As you can note in the preceding code, we extended the String class using the CustomStringConvertible protocol, which most of the Foundation class objects conform to. Using protocol extensions, they provide you with a wide variety of ways to extend the base classes so that you can add and implement your very own custom functionalities.

Summary

In this article, we explored how to go about downloading and installing Xcode development tools and then moved on to discussing and using playgrounds to write Swift code to get to grips with some of the Swift programming language features. Next, we looked at some of the newest features that come as part of the Swift 2.0 language.

Resources for Article:


Further resources on this subject:


You've been reading an excerpt of:

Apple Watch App Development

Explore Title