Optional means the value is Optional
type. It can be either nil
or a value. When working with cocoa api most of the method parameters are optional type. To get actual value from optional value you either use if-let
binding or force it to unwrap it with !
operator. Suppose ve have a value of a
optional type of Int
. Let’s define it first.
let a: Int? = 5
The ?
denotes it is an optional value. If you print this a
it will write Optional(5)
. Let’s get the actual value from it.
if let actualA = a {
println(actualA)
}
Now if a
is not nil
then the code inside if-let statement will be executed and it will print 5
on the console.
Optional types are for dealing with nil
values in swift. They provide extra safety when working parameters and variables. If a value is not optional than it can never be nil
. So we can safely do our work without worrying about nil
values.
solved Swift – what does Optional mean in log output? [closed]