1
votes

I'm learning Swift and I have a doubt regarding Implicitly Unwrapped Optionals.

I have a function returning a String optional:

func findApt(aptNumber :String) -> String?
{
    let aptNumbers = ["101", "202", "303", "404"]
    for element in aptNumbers
    {
        if (element == aptNumber)
        {
            return aptNumber
        }
    } // END OF for LOOP
    return nil
}

and an if statement to perform safe unwrapping, which uses an Implicitly Unwrapped Optional as its constant:

if let apt :String! = findApt("404")
{
    apt
    println(apt)
    println("Apartment found: \(apt)")
}

In the first line apt unwraps itself as it should (the results pane shows "404"), but in the other two lines apt does not unwrap: both the results pane and the console show that the printed values are Optional("404") and Apartment found: Optional("404"), and in order for 404 to appear on console I have to use the ! symbol, which, if I understand correctly, is only needed to manually unwrap regular Optionals.

Why does it happen?

My guess is that, when passed to println(), apt is implicitly converted from Implicitly Unwrapped Optional to regular Optional, which causes the Optional("404") text to appear, but I'd like some expert advice on the matter, as I'm just a beginner with the language.

1

1 Answers

2
votes

let apt :String! = findApt("404") won't unwrap the optional since you are explicitly using an Optional type which is String!

If you want to unwrap the optional use:

if let apt: String = findApt("404")
{
  ...
}

or better, using type inference:

if let apt = findApt("404")
{
  ...
}

In the first line apt unwraps itself as it should (the results pane shows "404"), but in the other two lines apt does not unwrap: both the results pane and the console show that the printed values are Optional("404") and Apartment found: Optional("404"), and in order for 404 to appear on console I have to use the ! symbol, which, if I understand correctly, is only needed to manually unwrap regular Optionals.

Why does it happen?

This is just how the console/playground displays the value. In your code example the apt is still an Optional.

You can check the type at runtime using dynamicType, i.e. println(apt.dynamicType)