「Swift」- AnyObject、Any、AnyClass的区别

1. AnyObject :代表任何class类型的对象实例。

class Man{
}
 
class Woman{
}
 
let man = Man()
let woman = Woman()
var arr:[AnyObject] = [man,woman]
 
for people in arr {
    if let m = people as? Man {
        println("这是个男人")
    }else if let w = people as? Woman {
        println("这是个女人")
    }
}

2. Any :范围更广,代表除函数外任何类型的实例。不仅包含object对象,还包含基本类型。

class Man{
}
 
class Woman{
}
 
var arr:[Any] = [Any]()
arr.apppend(1)
arr.append("hangge.com")
arr.append(Man())
arr.append(Woman())
 
for any in arr {
    switch any {
        case let any as Int:
            println("这是个Int类型")
        case let any as String:
            println("这是个String类型")
        case let any as Man:
            println("这是个男人类型")
        case let any as Woman:
            println("这是个女人类型")
        default:
            println("这是个未知类型")
    }
}

3. AnyClass是AnyObject.Type的别名而已。

看一下AnyClass的定义: typealias AnyClass = AnyObject.Type

你可能感兴趣的:(「Swift」- AnyObject、Any、AnyClass的区别)