user3742622
user3742622

Reputation: 1067

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

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?

Upvotes: 0

Views: 265

Answers (2)

Duncan C
Duncan C

Reputation: 131418

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.

Upvotes: 1

Rahul Mane
Rahul Mane

Reputation: 1005

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!))

Upvotes: 1

Related Questions