深入解析Swift中switch语句对case的数据类型匹配的支持

2020-01-08 23:11:34于丽
易采站长站为您分析Swift中switch语句对case的数据类型匹配的支持,Swift中switch...case语句支持多种数据类型的匹配判断,十分强大,需要的朋友可以参考下  

Swift可以对switch中不同数据类型的值作匹配判断:


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(Movie(name:"Ghostbusters", director:"Ivan Reitman"))

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

// zero as an Int
// zero as a Double
// an integer value of 42
// a positive double value of 3.14159
// a string value of"hello"
// an (x, y) point at 3.0, 5.0
// a movie called 'Ghostbusters', dir. Ivan Reitman

这里面会根据thing的值进行匹配,到对应的case当中。

今天突然想到一个问题,让我觉得有必要总结一下switch语句。我们知道swift中的switch,远比C语言只能比较整数强大得多,但问题来了,哪些类型可以放到switch中比较呢,对象可以比较么?

官方文档对switch的用法给出了这样的解释:

Cases can match many different patterns, including interval matches, tuples, and casts to a specific type.
也就是说除了最常用的比较整数、字符串等等之外,switch还可以用来匹配范围、元组,转化成某个特定类型等等。但文档里这个including用的实在是无语,因为它没有指明所有可以放在switch中比较的类型,文章开头提出的问题依然没有答案。

我们不妨动手试一下,用switch匹配对象:


class A {

}

var o = A()
var o1 = A()
var o2 = A()

switch o {
case o1:
  print("it is o1")
case o2:
  print("it is o2")
default:
  print("not o1 or o2")
}

果然,编译器报错了:“Expression pattern of type 'A' cannot match values of type 'A'”。至少我们目前还不明白“expression pattern”是什么,怎么类型A就不能匹配类型A了。