隐式解包选项和 println

Implicitly Unwrapped Optionals and println

我正在学习 Swift,我对隐式解包选项有疑问。

我有一个返回可选字符串的函数:

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
}

和执行安全展开的 if 语句,它使用隐式展开可选作为其常量:

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

第一行 apt 按原样展开自身(结果窗格显示 "404"),但在其他两行apt 行不展开:结果窗格和控制台都显示打印的值为 Optional("404")公寓找到:可选(“404”),为了让 404 出现在控制台上,我必须使用!符号,如果我理解正确的话,只需要手动打开常规 Optionals 即可。

为什么会这样?

我的猜测是,当传递给 println() 时,apt 被隐式地从隐式展开可选转换为常规可选,这导致 Optional(" 404") 文本出现,但我希望就此事获得一些专家建议,因为我只是该语言的初学者。

let apt :String! = findApt("404") 不会解包可选,因为您明确使用了 String!

的可选类型

如果要解包可选使用:

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

或更好,使用类型推断:

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?

这就是 console/playground 显示值的方式。在您的代码示例中,apt 仍然是 Optional

您可以使用 dynamicType 在运行时检查类型,即 println(apt.dynamicType)