11. Swift: Optionals, continue….

In previous article you saw that how to declare optional variable with ? operator and how to access the value with forced unwrapping technique by using ! operator.

var biology : Int?

biology = 50
println("Student got \(biology!) marks in Biology")

Swift provides another convenient way to declare optional variable

Implicitly unwrapped optional variable

You can declare unwrapped optional variable with ! operator.

var mathmarks : Int!

This optional works exactly the same like previous one but when you need to access the value, you do not need to use forced unwrapping technique.

mathmarks = 75

if mathmarks != nil{
    println("Student got \(mathmarks) in math")

Notice that you did not use \(mathmarks!) in println because this variable is already unwrapped in declaration.

nil-coalescing operator

What if the variable is nil and you want some other value in replacement. You can use traditional if else statement to solve this problem or you can use Swift magical nil-coalescing operator. Declare an optional string variable called name and use nil-coalescing operator  with ?? operators

var name : String?

let fullname = (name ?? "No name")

If name is not initialized with any string value, fullname will be assigned with “No name”

var name : String?
name = "Khan"
let fullname = (name ?? "No name")

Now value of fullname is “Khan”