简体   繁体   English

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

[英]difference between pattern matching and type casting

my understanding is that the 'as?' 我的理解是“为”? and 'as!' 并作为!' operators are for downcasting and 'as' for upcasting, disambiguation, bridging, and pattern matching. 运算符用于向下转换,“ as”用于向上转换,歧义消除,桥接和模式匹配。 But during pattern matching, the 'thing' of type 'any' is converted and dowoncasted to — for example — someInt as Int. 但是在模式匹配期间,类型为“ any”的“事物”将被转换并通过链表传输到例如int的someInt中。 why is the syntax not 'as?' 为什么语法不是“ as”? instead of 'as' ? 而不是“ as”? I'm confused why pattern matching is differentiated from type casting in this case? 我很困惑为什么在这种情况下模式匹配与类型转换有所区别?

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")
}
}

In the pattern-matching switch statement, a case is only accessed if thing 's type matches the type specified in that case . 在模式匹配switch语句,一个case ,如果仅访问thing的类型在该规定的类型相匹配 case The corresponding cast cannot fail (otherwise you wouldn't be in that case ) so you don't need to worry about unwrapping the cast with as? 相应的强制转换不会失败(否则您将不会在这种case ),因此您不必担心用as?展开强制转换as? or as! 还是as! .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM