Swift: Why all my optional variable looks like "Optional(305.502)"

268 Views Asked by At

I've just start learning swift. And I am a little be confused with optional types. I have some variable var theOptVar: Float? it can be nil so I make it optional with ?.
But when I'd like to get it somewhere at UI I see Optional(305.502).
Is there way to have optional var on UILabel without "Optional" word?

2

There are 2 best solutions below

0
Rahul Mane On BEST ANSWER

It is displaying “Optional” because you have changed its datatype from Float to Optional Float.
Due to this whatever value is there will be automatically wrapped into Optional text.

So if you don’t want to display optional word just extract the value out of it.

To do so add ! mark . This is forced unwrapping.

For eg.

var temp : Float?
temp = 60.5
println(Value \(temp!))
0
Duncan C On

You can either use the implicit unwrapping that Rob describes (aFloat!, which will crash if aFloat is nil)

or

Optional Binding

if let requiredFloat = aFloat
{
  //Code that only runs if aFloat is != nil
  println("aFloat = \(requiredFloat)")
}
else
{
  println("aFloat = nil")
}

Optional binding does two things for you: It checks to see if the optional is nil, and skips the block of code if it is nil. If it is NOT nil, it assigns the optional to a required constant which you can use inside your if code.