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 toUnwrap
. 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
?
and !
with a variables means both are optional
.!
this sign means implicitly unwrapped optional.?
sign with a variable, we have to unwrap when we use it.optional
cannot be nil. Ex :
var valueOne : Int = 4 // this cannot be nil
?
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 }
!
. 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