- AnyObject: 代表任意类的instance,是所有类都隐式遵守的协议;
- Any: 代表任意类型,包括funcation类型或者optional 类型;
- AnyClass: 代表任意实例的类型,本质是AnyObject.Type;
- T.self: 如果T是实例对象,返回的就是它本身,T 如果是类,那么返回的是 Metadata;
- T.Type: 一种类型,T.self 是 T.Type 类型
- type(of:): 用来获取一个值的动态类型
- Self:指的是当前类型(可以做约束使用)
AnyObject和AnyClass的关系:
public typealias AnyObject public typealias AnyClass = AnyObject.Type
其他使用示例,具体解释见注释(根据代码运行结果、自行体会)
class Person { var name: String? required init() {} static func clsMethod() { print("clsMethod") } } func testWrapped() { print(AnyObject.self) //打印:AnyObject print(AnyClass.self) //打印: AnyObject.Type let imageView = UIImageView() let controller = UIViewController() let p = Person() func test() {} let views: [AnyObject] = [imageView, controller, p] //这里不可以存放test print(views) //打印: [<UIImageView: 0x7f96f9307b30; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x600001959a40>>, <UIViewController: 0x7f96f9307d50>, SwiftTest.Person] let anys: [Any] = [test, imageView, controller, p] print(anys) //打印: [(Function), <UIImageView: 0x7f96f9307b30; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x600001959a40>>, <UIViewController: 0x7f96f9307d50>, SwiftTest.Person] let v1: Person.Type = Person.self //Person.Type 元类型 v1.clsMethod() //打印:clsMethod let v2: AnyClass = Person.self (v2 as! Person.Type).clsMethod() //打印:clsMethod let p2: Person.Type = type(of: p) let p3: Person = p2.init() p3.name = "lisi" print(p3.name ?? "") //打印:lisi p.name = "zhansan" let v3 = p.self print(v3.name ?? "") //打印:zhansan let p5: Person.Type = p2.self //p2.self是Person.Type类型 let p6 = type(of: Person.self) //p6是Person.Type.Type类型 let p7 = type(of: p2) //p7是Person.Type.Type类型 print(p6 == p7) //打印:true }
AnyObject可以作为协议的约束,只能被类所遵守
protocol ImageContainer: AnyObject { func test() } class Image: ImageContainer { func test() { } } struct Config: ImageContainer { //报错: Non-class type 'Config' cannot conform to class protocol 'ImageContainer' }
Self通常对协议或者返回值做限制,示例中代表只有继承自UIView的类或者子类才可以实现协议
protocol ImageContainer where Self: UIView { func test() -> Self } class SubView: UIView, ImageContainer { func test() -> Self { return self } } class Image: ImageContainer { //报错:'ImageContainer' requires that 'Image' inherit from 'UIView' }