Search code examples
iosswiftoptional-variables

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?


Solution

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