'如'在Swift switch语句中测试始终是真正的警告

时间:2017-04-15 12:32:00

标签: swift swift3

我在as Int案例中使用switch打开可选内容。它有效,但编译器会发出警告' as'测试永远是真的。当然,这是一个谎言,因为如果值不是asnil只会成功。

考虑这个最小的,可验证的例子:

var age: Int?

switch age {
case let y as Int:    // warning: 'as' test is always true
    print(y)
case nil:
    print("it is nil")
}

输出:

  

它是零

问题:什么是Swift在这里用这个警告思考,有没有更好的方法来展开值而不必使用强制解包?

4 个答案:

答案 0 :(得分:7)

这是as Int带来的错误 - 因为如果y不是nil,那么肯定是一个Int。

在这种情况下的正确语法(“有没有更好的方法来展开值而不必使用强制解包”)是:

    switch age {
    case let y?:
        print(y)
    case nil:
        print("it is nil")
    }

答案 1 :(得分:1)

正如@Hamish在评论中指出的那样,这是一个bug

错误报告中的注释建议使用.some(let y)解压缩可选项。

例如:

var age: Int? = 6

switch age {
case .some(let y) where y % 2 == 0:
    print("\(y) is even")
case .some(let y) where y % 2 == 1:
    print("\(y) is odd")
default:
    print("not odd or even, must be nil")
}

@Hamish再次提出使用句法糖case let y?的建议:

var age: Int? = 7

switch age {
case let y? where y % 2 == 0:
    print("\(y) is even")
case let y? where y % 2 == 1:
    print("\(y) is odd")
default:
    print("not odd or even, must be nil")
}

答案 2 :(得分:1)

Swift 4

警告''as'测试始终是真的'也会发生 “do-try-catch”,即

catch let error as Error {
  print("cannot perform the operation - \(error)") //'as' test is always true
}

删除类型转换,警告消失

catch let error {
  print("cannot perform the operation - \(error)")
}

这有效!

答案 3 :(得分:0)

您正在使用switch语句。 Switch语句与“if let”不同。 Switch假定您尝试区分不同类型,而不是某种类型和零之间。只需写下

if let y = age {
    // Not nil
} else {
    // nil
}