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!

No comments: