1.AnyObject
AnyObject表示任何类型的实例
class Person{
var name:String?
init(name:String) {
self.name = name
}
}
class Employee: Person {
var company:String?
init(name:String,company:String) {
self.company = company
super.init(name: name)
}
}
class Student: Person {
var school:String?
init(name:String,school:String) {
self.school = school
super.init(name: name)
}
}
let employee1 = Employee(name:"张三",company:"apple公司")
let employee2 = Employee(name:"李四",company:"google公司")
let members:[AnyObject] = [employee1,employee2]
for item in members{
let employee = item as!Employee
print("员工公司:\(String(describing: employee.company))")
}
2.Any类型
Any类型可以表示任何类型,比如类,函数,Int,String,元祖等
var things = [Any]()
things.append(42)
things.append("hello")
things.append((2,5))
things.append(Employee(name:"梅梅", company: "中国航天公司"))
things.append({(name:String) -> String in "你好,\(name)"})
for thing in things{
switch thing{
case let someInt as Int:
print("整数:\(someInt)")
case let someString as String:
print("字符串:\"\(someString)\"")
case let (x,y) as (Int,Int):
print("元组类型:\(x,y)")
case let employee as Employee:
print("员工:\(String(describing: employee.name)),公司:\(String(describing: employee.company))")
case let stringConverter as(String)->String:
print(stringConverter("小明"))
default:
print("其他")
}
}
注意
在switch语句的case语句里使用类型转换操作符as而不是as!,来检查和转换到一个明确的数据类型,在switch case语句中这样的检查总是安全的