Ensure that you are logged in and have the required permissions to access the test.


12
Introduction to Swift Programming Language
Computer Program
Swift-language

I recently started iOS application development with Swift. So, I will write quite frequently about it. In this post I will tell you what I felt about Swift till now. I am using XCode 6.0

The best place to get started with Swift is The Swift Programming Language: About Swift. Here are some of the points I think are important:

1.let is better than var.

By this, I mean that never declare a value as a variable if you know its value will never change.

2.If some variable can ever have a nil, declare it as an optional?.

As an example, the toInt function can return nil which means intFormOfNumber cannot be declared as Int

var number: String = "hello"
var intFormOfNumber: Int?
intFormOfNumber = number.toInt()

3.Use optional binding always to check if an optional contains a value. You will thank me later when your will never have a runtime error and your code will be readable as well.

4.Always use optional chaining as an alternative to forced unwrapping.

In the code below, it is a runtime error because type is a nil in Mamals.

class Mamals{
    var type : Human?
}

class Human{
    var legs = 2
}

var man = Mamals()
let manLegs = man.type!.legs

To avoid this, use optional chaining. The code will not give any error.

var man = Mamals()
if let manLegs = man.type?.legs{
    println(manLegs)
}else{
    println("manLegs is nil.")
}

5.Not sure why, but editing in Xcode becomes really(after every button you press, it stops for a second) slow if you do it in a single window. Always edit by double clicking on the filename in the navigation panel. This will open the code in another window.

6.break is not needed in switch unlike it was in C.

7.Use shorthands to reference closure arguments rather than by name.

func myClosure(value: Int, closure: (num: Int) -> (Int)) -> Int{
    return closure(num: value)
}

// This is accessing arguments by names
var y = myClosure(2, {
    value in
    return value
})

// This is accessing arguments by references
var x = myClosure(2, {
    return $0 * 4
})
Author

?