Introduction to Swift Programming 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.0The best place to get started with Swift isThe Swift Programming Language: About Swift. Here are some of the points I think are important:1.letis better thanvar.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 anil, declare it as an optional?.As an example, thetoIntfunction can return nil which meansintFormOfNumbercannot be declared as Intvar 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!.legsTo 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.breakis not needed inswitchunlike 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
})

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *