Getting started with Swift

If you are comfortable with playground file I would strongly suggest to use this Interactive Playground File from Apple


  • You need latest Xcode (Xcode 6 or up)
  • And for that you must have Yosemite (i.e. Mac OS 10.10 onwards)

Hello World

println("Hello, world!")

Variables and Constants

Define variables using var keyword var myVariable = value

Swift compiler will try to assign the type to myVariable based on the return type of value.

Define constants using let keyword let myConstant = value

If you do not want to assign a value yet to a variable then you have to hint the compiler of the object type. var myVariable: Dictionary

String interpolation

You can include a variable inside a string by using either of these syntax let myStringVar = "Hi"

Using + operator let myText = myStringVar + "!! Man"

Using () for string interpolation let myText2 = "\(myStringVar)!! Man"

Array Dictionary Tuples and other variable types

Arrays let todoItems = ["Go grocery", "Print important Docs", "Call Samantha"]

Dictionary let todoItems = ["important": ["Call Arun", "Reply to Samuel"], "not important": ["Go grocery", "Call Mom"]]

Tuples let myTuple = (3.14, "circle", "radius")

Tuples also contain multiple values but they can be any type. Array value must be of same type. Its helpful when a function returns multiple values.

Also tuples can also be defined as let (pi, shape, variable) = myTuple

and then you can access variables pi, shape and variables separately.

Constructors for base types

If you wish to initialise an empty array or dictionary, here is how its done. var todoItems = [String]() var todoItems = [String: Array]()


If statement

if condition1 {
} else if condition2 {
} else {


switch valueToCompareFrom {
case "value1":
// Do somethinghere
case "value2", "value3":
// Do something else
case let a where a.hasSuffix("novalue"):
// Handle it differently
// This runs if none of the above case matches


For in loop

for item in arrayVar {

There are c like while and do-while loops also.


func myFunc(param1: String, param2: Int) -> String {
return "Hello \(param1), count \(param2)."
myFunc("John", 400)

Functions now can be nested. Functions are first class type and so a function can return another function and also can take another function as argument.

Classes and Inheritance

class Electronics: Thing {
var voltage = 220
init(volatge: Int) {
self.volatge = voltage
func worksWithVolatge(volatge: Int) -> Bool {
return self.volatge == voltage
var computer = Electronics(100)
computer.voltage = 110
computer.worksWithVoltage(220) // returns false

Here class Electronics inherits from Thing class. init function is a constructor function Member variables can also have getters and setters. Static variables are defined using static keyword. Static functions are defined using class keyword.

Optional values

Optional values are a part of Apple’s type safety.

Gadget? is an optional type for Gadget class. It means that the instance variable is wrapped inside a construct which may return nil.

let optionalGadget: Gadget? = Gadget(voltage: 100)

You can’t access the the instance variable directly. You have to first unwrap it using the ? operator. If its nil then the assignment will fail. let voltage = optionalGadget?.voltage


enum iPhone: Int {
case Four = 1
case FourS, Five, FiveS, FiveC, Six, SixPlus
func printDescription() -> Void {
switch self {

The value of a enum can be accessed by .rawValue property. Instance of an enumeration from a raw value can be made by following constructor. let iPhone5s = iPhone(rawValue: 4)


As the name suggests it adds functionality to an existing class.

extension Int {
var simpleDescription: String {
return "The number \(self)"
mutating func adjust() {
self += 42


Introduction to Swift

Introduction to Swift

Official Page: Swift Language

Apple released Swift in mid 2014 and the aim was to ease the development process by introducing a language which is more readable, compiles faster and fun to work with. Some of its advantages are

Readable and Concise

  • In the web world Javascript is eating all other languages and so Apple guys made swift look more like Javascript.
  • Readable code is easier to scan and comprehend. So in Swift
    • Cleaner sytax for defining variables and blocks.
    • Header files were removed and modules were introduced.
    • Message passing syntax was removed.
    • Type guessing was introduced. Objects now were able to guess their type when first initialised.
    • Modules were auto imported.

Language Features

  • Better type safety.
  • Better Memory Management.
  • New types like tuples.
  • New functional paradigms like extensions.


  • Swift introduced Bridging headers which lets you include Objective C header files.
  • Now you can use the Objective C libraries without waiting it to get rewritten in Swift.
  • Converting large apps written in Objective C to Swift becomes smooth. You can iteratively convert your app to Swift.


  • Apple boasts about Swift performance in terms of compile and run times.


  • Swift project is now open source. This ensures that the language will evolve in a best possible way.


  • Playgrounds were introduced by Apple which are self contained sandbox apps. You can test your code in a playgroud file and view the output on the fly without compiling the whole thing.
  • As they are interactive, people have written books and tutorials on Swift using a single playground file.
  • You can write your interactive app documentation there.


Cons are generally bugs which will get fixed over a period of time.

  • Sometimes Xcode displays misleading errors and warnings.
  • Third party apps need to support Swift.