我在 switch
案例中使用 as Int
来解包一个可选的。它有效,但编译器发出警告 'as' test is always true。这当然是一个谎言,因为as
只有在值不是nil
时才会成功。
考虑这个最小的、可验证的例子:
var age: Int?
switch age {
case let y as Int: // warning: 'as' test is always true
print(y)
case nil:
print("it is nil")
}
输出:
it is nil
问题:Swift 在考虑这个警告时在想什么?是否有更好的方法来解包值而无需使用强制解包?
最佳答案
这是一个错误,由 as Int
引起——因为如果 y
不是 nil
,它肯定是一个 Int。
这种情况下的正确语法(“有没有更好的方法来解包值而不必使用强制解包”)是:
switch age {
case let y?:
print(y)
case nil:
print("it is nil")
}
关于swift - “as”测试在 Swift switch 语句中始终是 true 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426095/