Thursday, June 05, 2014

The Swift Programming Language - Lesson #3 - Dictionaries

In this lesson, you will learn how to create and use dictionaries in Swift.

Dictionaries

A dictionary is a collection of objects of the same type that is identified using a key. Consider the following example:

var platforms = [
    "Apple": "iOS",
    "Google" : "Android",
    "Microsoft" : "Windows Phone"

]

Here, platforms is a dictionary containing three items. Each item is a key/value pair. For example, "Apple" is the key that contains the value "iOS".

Unlike arrays, the ordering of items in a dictionary is not important. This is because an item is identified by the key and not the index. The above could also be written like this:

var platforms = [
    "Microsoft" : "Windows Phone",
    "Google" : "Android",
    "Apple""iOS"

]

The key of an item in a dictionary is not limited to String - it can be any of the hashable type (i.e. it must be uniquely representable). Th following example shows a dictionary using integer as its key:

var ranking = [
    1: "Gold",
    2: "Silver",
    3: "Bronze"

]

To access an item in a dictionary, specify its key:

let platform = platforms["Apple"]     // "iOS"

To know the number of items within a dictionary, use the count property:

var platformsCount = platforms.count  // 3

To replace the value of an item, specify its key and assign a value to it:

platforms["Microsoft"] = "WinPhone"

To remove an item from a dictionary, you can simply set it to nil:

platforms["Microsoft"] = nil;
platformsCount = platforms.count      // 2

The number of items inside the dictionary would now be reduced by one.

To insert a new item into the dictionary, you specify a new key and assign it a value, like this:


platforms["Samsung"] = "Tizen"

The value of a key can itself be another array as the following example shows:

var products = [
    platforms["Apple"]: ["iPhone", "iPad", "iPod touch"],
    platforms["Google"]: ["Nexus 3", "Nexus 4", "Nexus 5"],
    platforms["Microsoft"] : ["Lumia 920", "Lumia 1320","Lumia 1520"]

]

To access a particular product in the above example, you would first specify the key of the item you want to retrieve, followed by the index of the array, like this:

var product1 = products["Apple"][0]

Mutabilities of Dictionaries

When creating a dictionary, its mutability (its ability to change its size after it has been created) is dependent of you using either the let or var keyword. If you used the let keyword, the dictionary is immutable (its size cannot be changed after it has been created) as you are creating a constant. If you used the var keyword, the dictionary is mutable (its size can be changed after its creation) as you are now creating a variable.

See Also
Arrays

Wednesday, June 04, 2014

The Swift Programming Language - Lesson #2 - Arrays

In this lesson, you will learn how to create and use arrays in Swift.

Arrays

An array is a collection of objects - and the ordering of objects in an array is important. The following statement shows an array containing 3 items: 

var OSes = ["iOS", "Android", "Windows Phone"]

In Swift, you create an array using the [] syntax. The compiler automatically infers the type of items inside the array; in this case it is an array of String elements.

Note that if you attempt to insert an element of a different type, like this:

var OSes = ["iOS""Android""Windows Phone", 25]

The compiler will assume the elements inside the array to be of protocol type AnyObject (which is similar to id in Objective-C and System.Object in .NET), which is an untyped object.

In general, most of the time you want your array to contain items to be of the same type, and you can do so explicitly like this:

var OSes:String[] = ["iOS", "Android", "Windows Phone"]

This forces the compiler to check the types of elements inside the array and flag an error when it detects otherwise.

The following example shows an array of integers:

var numbers = [0,01,2,3,4,5,6,7,8,9]

To retrieve the items inside an array, specify its 0-based index, like this:

var item1 = OSes[0]   // "iOS"
var item2 = OSes[1]   // "Android"
var item3 = OSes[2]   // "Windows Phone"

To insert an element at a particular index, use the insert() function:

OSes.insert("BlackBerry", atIndex: 2)

item3 = OSes[2]       // "BlackBerry"
var item4 = OSes[3]   // "Windows Phone"

Note that in the above function call for insert(), you specify the parameter name - atIndex. This is known as an external parameter name and is usually needed if the creator of this function dictates that it needs to be specified.

We shall talk more about this when we discuss functions. 

To change the value of an existing item in the array, specify the index of the item and assign a new value to it:

OSes[3] = "WinPhone"

To append an item to an array, use the append() function:

OSes.append("Tizen")

Alternatively, you can also see the += operator to append to an array, like this:

OSes += "Tizen"

You can append an array to an existing array, like this:

OSes += ["Symbian", "Bada"]

To know the length of an array, use the count property:

var lengthofArray = OSes.count

To check if an array is empty, use the isEmpty() function:

var arrayIsEmpty = OSes.isEmpty

You can also remove elements from an array using the following functions:

OSes.removeAtIndex(3)              // removes "WinPhone"
OSes.removeLast()                  // removes "Bada"

OSes.removeAll(keepCapacity: true) // removes all element

For the removeAll() function, it clears all elements in the array. If the keepCapacity parameter is set to true, then the array will maintain its size.

Mutabilities of Arrays

When creating an array, its mutability (its ability to change its size after it has been created) is dependent of you using either the let or var keyword. If you used the let keyword, the array is immutable (its size cannot be changed after it has been created) as you are creating a constant. If you used the var keyword, the array is mutable (its size can be changed after its creation) as you are now creating a variable.

OK for today! Look out for the next lesson soon!

Tuesday, June 03, 2014

The Swift Programming Language - Lesson #1

Apple has surprised quite a number of developers at WWDC 2014 yesterday with the announcement of a new programming language - Swift. The aim of Swift is to replace Objective-C with a much more modern language and at the same time without worrying too much about the constraints of C compatibility. Apple itself touted Swift as the Objective-C without the C.

For developers already deeply entrenched in Objective-C, it is foreseeable that Objective-C would still be the supported language for iOS and Mac OS X development in the near and immediate future. However, signs are all pointing that Apple is intending Swift as the future language of choice for iOS and Mac development.

While groans can be heard far and near about the need to learn another programming language, such is the life of a developer. The only time you stop learning is when the end of the world is near (OK, you get the idea). So, in the next couple of weeks and months, I am going to walk you through the syntax of the language in bite-size format (so that you can probably read this on the train or on the bus home), and hopefully give you a better idea of the language.

So, let the journey begin!

Constants

In Swift, you create a constant using the let keyword, like this:

let radius = 3.45
let numOfColumns = 5

let myName = "Wei-Meng Lee"

Notice that there is no need to specify the data type -  they are inferred automatically. If you wish to declare the type of constant, you can do so using the : operator followed by the data type, like this:


let diameter:Double = 8;

The above statement declares diameter to be a Double constant. You want to declare it explicitly because you are assigning an integer value to it. If you don't do this, the compiler will infer and assume it to be an integer constant.

Variables

To declare a variable, you use the var keyword, like this:

var myAge = 25
var circumference = 2 * 3.14 * radius

Once a variable is created, you can change its value:

circumference = 2 * 3.14 * diameter/2

In Swift, values are never implicitly converted to another type. For example, suppose you are trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() function to convert the value of circumference to a string value before concatenating it with another string:

var strResult = "The circumference is " + String(circumference)

Including Values in Strings

One of the dreaded tasks in Objective-C is to insert values of variables in a string. In Swift, this is very easy using the \() syntax. The following example shows how:

var strName = "My name is \(myName)"

You can also rewrite the earlier statement using the following statement:

var strResult = "The circumference is \(circumference)"

OK for now, stay tuned for the next lesson!