swift - “as”测试在 Swift switch 语句中始终是 true 警告

标签 swift swift3

我在 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/

相关文章:

ios - 订阅 channel 不起作用 - 使用 Swift 解析

arrays - 从值为空字符串的数组中删除字典(使用高阶函数)

swift - CocoaPods 的 Xcode 10.1 Swift 编译器错误

ios - swift3中的编译错误:“AnyObject”不是“NSObject”的子类型

ios - 使用 setContentOffset 滚动到特定页面

ios - 如何检查哪个文本字段被按下?

ios - 扫描二维码后如何进入新的 View Controller ?

ios - Swift 3 如何解决 func 中的 EXC_BAD_ACCESS

swift3 - Swift 4 Migration - 从非协议(protocol)、非类 AnyObject 继承

swift - 手动设置导航项的 titleView 未垂直对齐