首页 文章

无法强行打开值

提问于
浏览
-4
var tuples: String! = "subash"
if let goin = tuples {
    print(goin!)
}

我收到此错误:

无法强制解包非可选类型String的值

我不知道发生什么不断的goin和元组一样,但为什么当我强制打开包装时它会显示错误

这不是上面的代码,而是运行良好:

var tuples: String! = "subash"
print(tuples!)

但是,我需要解决上述问题

1 回答

  • 0

    如果您知道选项如何运作,这是正常的 .

    在if语句中,正确的表达式必须是Optional或Implicitly Unwrapped Optional,但不是“normal”值 .

    这是正确的代码:

    let tuples: String! = "subash"
    
    if let goin = tuples {
        print(goin) // NO NEED to unwrap, because going IS NOT Optional
    }
    

    这段代码运行正常的原因:

    var tuples: String! = "subash"
    print(tuples!)
    print(tuples)
    

    ...是因为元组是Implicitly Unwrapped Optional类型 .

    但是,一般情况如下:

    let myVar: String! = "some string"
    
    if let myNewVar = myVar {
        // Some code...
    }
    

    ... myVar 始终是隐式解包可选,而 myNewVar 是String类型,因为可选解包如何与 if let 语句一起使用 .

    最后,如果我们以这种方式展开值:

    let myVar: String! = "some string"
    
    if let myVar = myVar {
        // Some code...
        print(myVar)
    }
    

    打印的值是 temp myVar ,其类型为 String ,并且会隐藏我们最初声明的Implicitly Unwrapped myVar 变量 .

相关问题