Search code examples
swiftconcatenationoption-type

What is the difference between using optional and not using optional to declare non assign variables in swift 3.0


We can declare nil variables like below in swift 3.0

var aString : String?

then we can assign values after like this

aString = "hello"

then if we concatenate , we have to cast it like below

var newone: String = aString! + " stackoverflow"

But We can do the same thing like below and when we concatenate, we do not need to Unwrap. why is that

.

var bStirng : String

bStirng = "hello"
var newBString : String = bStirng + " StackOveflow"

is the only advantage of using optional is that we can check whether the variable is nil or not


Solution

    • using ? and ! with a variables means both are optional.
    • ! this sign means implicitly unwrapped optional.
    • And if we use ? sign with a variable, we have to unwrap when we use it.
    • In my case, a varible without optional cannot be nil. Ex :

    var valueOne : Int = 4 // this cannot be nil

    • And using ? menas its type is optional

    var valueTwo :Int? = 8 //type of this variable is Optional Int and this can be nil. and also when we use this we have to unwrap it and should check whethe this is nil or not like below

    valueOne + valueTwo!

    if let newVal = valueTwo{
         valueOne + newVal //check the value is nil or not
    }
    
    • Finally using !. implicitly unwrapped optional.

    var valueThree : Int! = 12 // type of this variable is implicitly unwrapped optional Int we do not need to unwrap when we do any operation with it like below. this also can be nil

    valueOne + valueThree