2017-07-26 67 views
1

我的理解是,'as?'并作为!'运算符是向下转换的,“as”用于上传,消歧,桥接和模式匹配。但是在模式匹配过程中,'any'类型的'thing'被转换并且dowoncasted为 - 例如 - someInt作为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") 
} 
} 

回答

2

在模式匹配switch声明,一个case如果在该指定casething的类型匹配的类型仅访问。相应的阵容不会失败(否则你不会在case),所以你不必担心用as?as!解开演员阵容。