模式匹配和类型转换之间的区别

时间:2017-07-26 15:10:32

标签: ios swift swift3

我的理解是'as?'并作为!'运营商用于向下转发和'as'用于向上转换,消除歧义,桥接和模式匹配。但是在模式匹配期间,'any'类型的'thing'被转换并被降级为 - 例如 - someInt as Int。为什么语法不是'as?'而不是'as'?我很困惑为什么在这种情况下模式匹配与类型转换不同?

var things = [Any]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append({ (name: String) -> String in "Hello, \(name)" })

for thing in things {
switch thing {
case 0 as Int:
    print("zero as an Int")
 case 0 as Double:
    print("zero as a Double")
case let someInt as Int:
    print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
    print("a positive double value of \(someDouble)")
case is Double:
    print("some other double value that I don't want to print")
case let someString as String:
    print("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
    print("an (x, y) point at \(x), \(y)")
   case let stringConverter as (String) -> String:
        print(stringConverter("Michael"))
    default:
        print("something else")
}
}

1 个答案:

答案 0 :(得分:2)

在模式匹配switch语句中,case仅在thing的类型匹配时才会访问case { {1}}。相应的演员阵容不会失败(否则你不会在case中),所以你不必担心用as?as!展开演员表。< / p>