Swift - AnyObject与Any的区别

时间:2022-05-01 20:46:20
1,AnyObject :代表任何class类型的对象实例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 :范围更广,代表除函数外任何类型的实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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("这是个未知类型")
    }
}