Swift 为不确定类型提供了两种特殊的类型别名:
Any
可以表示任何类型,包括函数类型。
AnyObject
可以表示任何类类型的实例。
只有当你确实需要它们的行为和功能时才使用 Any
和 AnyObject
。最好还是在代码中指明需要使用的类型。
这里有个示例,使用 Any
类型来和混合的不同类型一起工作,包括函数类型和非类类型。它创建了一个可以存储 Any
类型的数组 things
:
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")) things.append({ (name: String) -> String in "Hello, \(name)" })
things
数组包含两个 Int
值,两个 Double
值,一个 String
值,一个元组 (Double, Double)
,一个 Movie
实例“Ghostbusters”
,以及一个接受 String
值并返回另一个 String
值的闭包表达式。
你可以在 switch
表达式的 case
中使用 is
和 as
操作符来找出只知道是 Any
或 AnyObject
类型的常量或变量的具体类型。下面的示例迭代 things
数组中的每一项,并用 switch
语句查找每一项的类型。有几个 switch
语句的 case
绑定它们匹配到的值到一个指定类型的常量,从而可以打印这些值:
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 movie as Movie: print("a movie called \(movie.name), dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("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 // Hello, Michael
注意
Any 类型可以表示所有类型的值,包括可选类型。Swift 会在你用 Any 类型来表示一个可选值的时候,给你一个警告。如果你确实想使用 Any 类型来承载可选值,你可以使用 as 操作符显式转换为 Any,如下所示:
let optionalNumber: Int? = 3 things.append(optionalNumber) // 警告 things.append(optionalNumber as Any) // 没有警告