Home Mobile Application Development with Swift

Application Development with Swift

By Hossam Ghareeb
books-svg-icon Book
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Publication date:
August 2015
Publisher
Packt
Pages
144
ISBN
9781785288173

 

Chapter 1. Hello Swift

Welcome to the developing applications with Swift book. It's my pleasure to talk about iOS development and Swift. This book assumes that you have some basic experience in iOS development, and a little experience of using Swift. If you don't have any experience of Swift, don't worry, just go ahead with us and be prepared to master the iOS development using Swift. I believe in learning by example methodology and, starting from Chapter 3, Touch ID, we will introduce the new technology of iOS 8, and write a simple demo on it using Swift.

In this chapter, we will talk about the Swift programming language, and get our hands dirty with Swift. If you are familiar with Swift, you can either skip this chapter, or you can review your Swift knowledge. We will talk about the Swift language and its features, and how to try it using Playgrounds in Xcode 6. Playground is a new, awesome, and innovative feature that allows you to try any piece of code, and see the results without explicitly running, or even compiling your code. You will become familiar with the code structure, and some important data types such as arrays, dictionaries, and so on.

 

Introduction to Swift


Swift is a new (Apple has open sourced it!), scripting, programming language for developing apps for iOS, OS X, and watchOS. Apple has introduced this language to make things easier and fun. Unlike Objective-C, Swift is not a superset of C programming language. But believe me, it has the power of both C and Objective-C.

It's the first time we have an alternative to Objective-C, since Apple introduced iOS and OSX development tools. As a new programming language, Swift introduces many new features and concepts that did not exist in Objective-C, and we will talk about them in next sections. For Objective-C developers, Swift will be familiar to them, as it adopts the readability of Objective-C's named parameters. Swift is a friendly programming language. It is so expressive and funny even for new programmers who have no experience with Objective-C.

Like Objective-C, Swift is an OOP language and you can easily create classes, objects, methods, and properties. Swift is built to make developers write safe code, and you will feel this when you will start working with it. An example of this is that you can't use variables without initialization. Swift saves you from making silly errors that you could make, such as using variables before initialization.

Don't hesitate to work with Swift, and give it a shot. Swift co-exists alongside your existing Objective-C code, and is easy to work with. You can also replace your existing Objective-C code with Swift, or start your project from scratch with Swift as your primary development language.

Make sure that you are familiar with Swift features to feel its power, and enjoy it. Some of these features are new for Objective-C developers, and these will let you love Swift, as I do:

  • Closures

  • Tuples

  • Range operators

  • Generics

  • Structures

  • Functional programming patterns

 

Playgrounds


We mentioned the Playground feature earlier—it is a new innovative feature supported in Xcode 6 and higher. It gives you the ability to try any piece of code in Swift, and see the results immediately without the need to compile or run the code. So, imagine that you are learning Swift, or working in a project with Swift, and you need to try some code, and check its result. If you are in Objective-C, you need to create a new project, write the code, build, run, and open the simulator to see the results! Very time consuming, isn't it? I mean, it's time consuming here, in the learning track, but after you master the language, you don't need to use Playgrounds. You may just need to use it in test or to check something. To play with the Playground feature use the following steps:

  1. In Swift and Xcode 6, or higher, just create a new playground (as shown in the following screenshot) or open an existing one by choosing the .playground file in a navigator:

  2. Now, enter Swift code in the .playground file, and enjoy the results in the right-hand side sidebar. Xcode evaluates your code while you type it, and for each statement, Xcode displays the results of it in the right-hand side sidebar.

As you see, each line of code is examined, and its result is shown in the results sidebar, in the right-hand side. Even the for loop statement shows you how many times the entire code was executed. To see the value of any variable, just write it in a separate line, and check its value in the right-hand side sidebar. (Check line 11 in the preceding screenshot).

Another feature of Playground is the value history. In the previous for loop, we have a piece of code that is executed repeatedly, right? But I want to know what is going on in each iteration. Xcode helps you with this by providing the history button in the results sidebar, on the line containing the number of times. Once you click on it, it displays a complete graph (timeline) for the values over the time. In the graph, x axis represents time, and y axis represents the value at this time (this iteration).

Once you click on the circle in the results view, you can see the value of this iteration:

Also, keep in mind that Playground includes the standard editing features of Xcode, such as code completion, error checking, syntax correction, and suggestions.

 

The code structure


Before starting to write Swift, you have to be aware of its structure, as it is a very important thing to know in any programming language.

As we said earlier, Swift is not a superset of C. For sure it's influenced by C and Objective-C but easier and fun to use than both.

I will share with you a piece of code in Swift to show its structure:

import UIKit

let pi = 3.14
//Display all even numbers from 0 to 10
for i in 0...10
{
    if i % 2 == 0
    {
        println("\(i) is even")
    }
}

func sayHello(name: String = "there")
{
    
    println("Hello \(name)")
}

sayHello(name: "John") // will print "Hello John" 
sayHello() //Will print "Hello there", based on default value

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 direct to you.

If you check this code, you will find that we don't use semicolons. This is because in Swift they are optional. However, compiler will not complain if you do use them. The only area where semicolons are required is when you write multiple statements in the same line.

In Swift, you use var for variables, and let for constants; but this doesn't mean that Swift is not a typed language. The compiler, based on the initial value, identifies the type implicitly. But in some cases, you have to write the type if you don't set an initial value; or the initial value is not sufficient to identify the type.

Consider the following code for example:

var count = 5
var msg : String
var total : Double = 0

In this code, the count variable is of the Int type, because its initial value is in integer. In the msg variable, we didn't set an initial value, so we will have to explicitly write the type of the msg variable. The same is applicable for total; we need it to be of the Double type but as its initial value is not sufficient, the compiler will consider it as Int.

In Swift, you will see that there is no main function to start with, as the code written in the global scope is considered as the start of your program. So, you can imagine that a single line of code in Swift can be considered as a program!

The last thing I want to mention is that curly braces are very important in Swift, as they are mandatory in any control flow statements, such as if, while, and so on.

 

Arrays


An array is every developer's best friend and saves the collection of data in an ordered list. In Swift, an array is very easy to use and contains many helpful methods for use. Before exploring it, we have to clarify some important points.

Array by default is mutable so that it accepts adding, changing, or removing items from it, except if we define it as a constant, using let. In this case, it will be immutable, as it becomes constant.

In Objective-C, you can save any type of object, and you won't have to specify any information about their type. In Swift, arrays are typed; this means that the type of item should be clear, and all the items should be of the same type. The type can be defined explicitly, or it can be inferred.

An array doesn't have to be of a class type. So, you can create an array of Int, and in such a case, you can't insert any other value than the Int type.

The following are examples to make these points clear:

let languages = ["Arabic", "English", "French"]
//Here type is inferred as String, So this Array is of type String
//Also this array is immutable as it defined as let

var primes :[Int] = [2, 3, 5, 7, 11]
//Type is written explicitly

primes.append(13) //mutable array as it defined as var

Initializing an array

To initialize and create an array, you can use the previous ways with initial values, or you can either create it empty, or by using repeating values:

As you see in the example, it's very easy to initialize empty arrays, or arrays with repeating values. Swift also provides a great feature to append two arrays that result in a new array.

Iterating over arrays

The explanation is not complete without mentioning how to iterate over an array. Actually, iterating over an array in Swift is very easy and straightforward. To iterate over values of an array, you will use the for-in loop like this:

var seasons = ["Winter", "Spring", "Summer", "Autumn"]

for season in seasons{
    println(season)
}
/*
Winter
Spring
Summer
Autumn
*/

And if you want the index of the value in each iteration, you can use the enumerate method. In each iteration, the method returns a tuple that is composed of an index and value of each item in the array. Check the next example to make things clear:

for (index, season) in enumerate(seasons){
    
    println("Season #\(index + 1) is \(season)")
}
/*
Season #1 is Winter
Season #2 is Spring
Season #3 is Summer
Season #4 is Autumn
*/

For all those who don't know tuples, tuples in Swift are used to create and pass around a group of values. It can be used to return multiple values from a function in a single group.

Appending items

You can append items easily by using the append method, which appends an item at the end of an array. To append multiple items at once, append an array of these items.

You can also use the insert method that inserts items at a specific location.

var nums = [1, 3]            // [1, 3]
nums.append(4)              //  [1, 3, 4]
nums.insert(5, atIndex: 1) //   [1, 5, 3, 4]
nums += [10, 11]          //    [1, 5, 3, 4, 10, 11]

Removing and updating items

An array has a built-in removeAtIndex function to remove an item at the index and a removeLast function to remove the last item. These functions are awesome. While you call them, they return the deleted item at the same time and thus, you don't have to write another line of code to grab the item before deleting it.

nums.removeAtIndex(1) // return 5
nums.removeLast()    //  return 11
nums                //   [1, 3, 4, 10]
nums[0...2] = []   //    array now is [10]

In this code we removed an item at index 1 and the last item, as you see in the first two lines.

Another great feature in Swift is using ranges, which we used for replacing the items in the range from 0-2. This replaces the first three items with an empty array. That means the first three items have been removed. You can also replace it with an array containing data. Now, replace the items in the range with the items in the array. The most important thing is to be careful with the ranges that are used, and make sure that they are an inbound of the array. The out of bound ranges will throw exceptions.

 

Dictionaries


Dictionaries in Swift are like arrays in special characteristics, such as mutable and strongly typed. Dictionary is mutable by default, except if used with let. Also keys and values should be of the same type.

The dictionary type is inferred by the initial values, or you can explicitly write it using the square brackets [keyType, valueType].

Initializing a dictionary

To initialize a dictionary, you have two options. The first option is to create an empty one with no data. You can create it like this:

var dic1 = [String:Int]() // 0 key/value pairs

As we see in this case, we had to explicitly write the type of keys and values.

In the second option, you have the predefined values like this:

var dic2 = ["EN" : "English", "FR" : "French"]
//["EN": "English", "FR": "French"]

Here we didn't write the type of keys or the values, as it was inferred from the initial values.

Appending or updating values

Updating or appending a value with a key in a dictionary is very similar, and can be done like this:

dic2["AR"] = "Arabic" //Add
dic2["EN"] = "ENGLISH" //update
//["EN": "ENGLISH", "FR": "French", "AR": "Arabic"]

As you can see, in the first line it will create a new record in the dictionary, because the "AR" key did not exist before. In the second line as the "EN" key exists, it will update each of its values with the given one. Very simple right!

Another method to update a value for the key in the dictionary is to call updateValue(val, forKey:). Take a look at the following example:

dic2.updateValue("ARABIC", forKey: "AR") //returns "Arabic"
//dic2 now is ["EN": "ENGLISH", "FR": "French", "AR": "ARABIC"]

As you see in the code, this method returns the old value after updating the new value. So, if you want to retrieve the old value after the update function is done, this method is the best choice.

Removing items from the dictionary

This is the same as updating values. You have two ways to remove items from dictionary. The first is to set the value of the key as nil, and the second is to call the removeValueForKey(key) method. This method also returns the old value before deleting it.

dic2["AR"] = nil
dic2.removeValueForKey("FR") //returns French
//["EN": "ENGLISH"]
dic2["FR"]  // Returns nil
 

Enum


Enumeration is a very useful concept that is used to group related values together and define a new type for them. You must be familiar with enumeration in Objective-C or in C. Swift added new flavors to enum, and made it more flexible and easy to use.

To create enum in Swift, use the enum keyword, and then you can list all the possible cases after the case keyword:

enum LevelDifficulty{
    case Easy
    case Medium
    case Hard
    case Advanced
}

In the preceding code, we defined the new type as LevelDifficulty to group the related values of difficulties together (Easy, Medium, Hard, and Advanced). To use this enum, you can easily create variables with the LevelDifficulty type:

var easyMode = LevelDifficulty.Easy
//Type is inferred as LevelDifficulty

var mode : LevelDifficulty
mode = .Hard

As we see in this example, there are various ways to create enum. In the second one, for the variable mode, we set the type first, and then gave it a value. To set the value of a variable, we use a . (dot) operator.

Using enumerations with the switch statement

Swift makes life easy with enum. We can see this in the following example:

var power :Int
switch mode
{
case .Easy:
    power = 20
case .Medium:
    power = 30
case .Hard:
    power = 50
case .Advanced:
    power = 90
}

Very easy, isn't it? But take care of some the very important notes in the switch statement while using it in Swift:

  • It has to be exhaustive, which means that you have to cover all the possible values of enum, and list them as cases, or use the default case.

  • Swift doesn't support fallthrough. Unlike other languages, Swift doesn't fall through the bottom of each switch case into the next one. The switch statement finishes its execution as soon as a switch case is matched without explicitly writing a break statement. For sure, this makes your code safer by avoiding the execution of more than one switch case, by forgetting to add a break statement!

Enumerations with associated values

Swift gives enumerations another flavor and a great feature. This enables you to store the additional information for each member value. These associated values can be any given type, and can also be different for each member value. If you feel confused, look at the next example:

enum MissionState{
    case Accomplished(Int)
    case Attempted(String, Int)
    case UnAttempted
}

In this enum, in the case of Accomplished, we provide an integer value for it, which will represent the number of stars earned in this mission. In the case of Attempted, we provide two values for it. One is the string that represents the most progress achieved, and the other is the integer value for the number of attempts. The last one is UnAttempted, where we don't have to provide any additional information.

So now, let's see how to use this type of enumerations:

var state = MissionState.Accomplished(3)
var attemptState = MissionState.Attempted("80%", 3)

It is very easy to use this type of enumeration in the switch statement:

switch attemptState
{
case .Accomplished(let stars):
    println("Mission accomplished with \(stars) stars")
case .Attempted(let progress, let count):
    println("Mission attempted \(count) times with most progress \(progress)")
case .UnAttempted:
    println("UnAttempted")
}

To use the associated values in enumerations, Swift gives you the ability to label or describe these different values. This will make your code more readable and easy to use. To recreate our previous enum with labels, use the following code:

enum MissionState{
    case Accomplished(stars:Int)
    case Attempted(missionProgress:String, attemptsCount:Int)
    case UnAttempted
}

var state = MissionState.Accomplished(stars:3)
var attemptState = MissionState.Attempted(missionProgress: "80%", attemptsCount: 3)

You can see how the labels make the code very understandable and easier to read.

 

Functions


In Swift, it's very easy to create the functions using the func keyword, followed by the function name and parameters between the parentheses. Parentheses are required even if the function doesn't take parameters. So we will use parentheses without writing anything in between. For some other languages we need to use the void keyword for the function that doesn't take parameters. Parameters are comma separated and each one is combined with two items: the name and the type of parameters, separated by : (colon). Check this example of a simple function:

func sayHi(name:String)
{
    println("Hi \(name)")
}

sayHi("John") //Hi John

One of the great features that I love in Objective-C is that you can write a full description for each parameter in methods, which helps everyone, working in the project, to understand the code. The same is here in Swift; you can label parameters more easily. To do so, just type the name (description) before the parameter, or add # before the name of parameter, if the name is sufficient as a description and meaningful. Check these two examples:

func joinStrings(string1 str1:String, toString str2:String, joinWith j:String)
{
    println(str1 + j + str2)
}

joinStrings(string1: "John", toString: "Smith", joinWith: ",") //"John,Smith"

func joinStrings2(#string1:String, #toString:String, #glue:String)
{
    println(string1 + glue + toString)
}

joinStrings2(string1: "John", toString: "Deo",glue: "/") //"John/Deo"

As we saw in the first method, we wrote the description for each parameter, so that the code would be readable and understandable. In the second one, the parameter names were self-explained, and they needed no explanation. In such a case, we just added # before them, and then the compiler treated them as labels for parameters.

Like any function in any language, Swift may return results after the execution. Functions can return multiple values and not just a value like Objective-C, thanks to tuples! To do this, just write -> after the parentheses, and then add a tuple that describes the results:

func getMaxAndSum(arr:[Int]) -> (max:Int, sum:Int)
{
    var max = Int.min
    var sum = 0
    for num in arr{
        if num > max
        {
            max = num
        }
        sum += num
    }
    return(max, sum)
}

let result = getMaxAndSum([10, 20, 5])
result.max //20
result.sum //35
 

Closures


Think of closures as a piece of code or functionality to pass around in your code. Closures in Swift are very similar to blocks in C and Objective-C. Closures in Swift are the first class type and it is allowed to be returned or passed as a parameter. And as we will see, functions are just special instances of closures. The general formula for closures is like this:

{ (params) -> returnType in
    
    //statements
}

As you can see, we opened curly braces, and then we added the necessary parameters followed by the return type and the in keyword. Knowing this formula will help you a lot in using closures, and you will not feel any frustration using it.

This is an example of using closures in sorting the collection of data:

var nums = [10, 3, 20, 40, 1, 5, 11]
sorted(nums, { (number1, number2) -> Bool in
    return number1 > number2
})
//[40, 20, 11, 10, 5, 3, 1]

Here, the closure is used to identify the comparison result of any two numbers. As we saw, the closure takes two parameters and returns a Boolean, that is the result of the comparison.

 

Summary


In this chapter, we saw what Swift is, and how the code structure works. We saw its new features by using arrays, dictionaries, functions, and closures. We also learned how to use Playground to try any piece of code in Swift anytime, without creating a new project, or even compiling and building your project. At the end of this chapter, you have the basic skills to write Swift code. In the next chapter, we will talk about some advanced features in Swift, including casting and checking, protocols, delegation, generics, memory management, and much more. Stay tuned!

About the Author
  • Hossam Ghareeb

    Hossam Ghareeb is a software engineer who graduated from Alexandria University in 2012. He found his passion in mobile development, especially iOS development. Currently, he is a senior iOS developer at Noon e-commerce in Dubai. Hossam has built his experience by learning tips and tricks from the managers he works with, open source projects, and online tutorials. He discovered that the best way to pay this back is to share his experience with others and help people get experience in iOS development.

    Browse publications by this author
Latest Reviews (3 reviews total)
Application Development with Swift
Unlock this book and the full library FREE for 7 days
Start now