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?
Asked
Active
Viewed 265 times
0

Rahul Mane
- 1,005
- 18
- 33

user3742622
- 1,037
- 3
- 22
- 40
-
about which you are sure that there will be value so remove optional sign "?" – Fatti Khan Mar 28 '15 at 10:47
-
You can use ther implicitly unwrapped syntax of `Float!` rather than `Float?`. It's still an optional, but will be implicitly unwrapped every time you use it (so make sure it's not `nil` before you try to use it). – Rob Mar 28 '15 at 11:46
2 Answers
1
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!))

Rahul Mane
- 1,005
- 18
- 33
1
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.

Duncan C
- 128,072
- 22
- 173
- 272