Implicitly Unwrapped Optionals and println

半腔热情 提交于 2019-12-08 08:26:37

问题


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:


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)



来源:https://stackoverflow.com/questions/32157667/implicitly-unwrapped-optionals-and-println

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!