Getting started with Swift

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

Requirements

  • 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]()

Conditionals

If statement

if condition1 {
} else if condition2 {
} else {
}

Switch

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

Loops

For in loop

for item in arrayVar {
}

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

Functions

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
super.init()
}
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

Enums

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

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)

Extensions

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
}
}
println(7.simpleDescription)

Related Posts

Leave a comment

Hey, so you decided to leave a comment! That's great. Just fill in the required fields and hit submit. Note that your comment will need to be reviewed before its published.