swift中的Any、AnyObject、X.self、X.Type、AnyClass、Self

Any、AnyObject

Any: 類似于OC中的instanceType,可以代表任意類型
AnyObject: 代表任意 類 類型,像枚舉、結(jié)構(gòu)體,都不行

is as

is:判斷是否是某種類型(既可以是類與類之間的判斷,也可以是類與協(xié)議之間的判斷)
as:做類型強(qiáng)制轉(zhuǎn)換

protocol testProtocol {}
class Animal {}
class Person: testProtocol, Animal {}
var p = Person()
print(p is Animal) // true
print(p is testProtocol) // true
ptint(p is Person) // true

var num: Any = 10;
print(num is Int) // true

X.self、X.Type、AnyClass

X.self: 是一個元類型(metadata)的指針,存放著類型相關(guān)的信息
x.self屬于X.type類型

先來說下X.self :

class Person {}
var P = Person()

其內(nèi)存分配如下:


image.png

還有一點(diǎn)在swift中不像OC一樣需要繼承一個通用的基類NSObject,在swift中如果不繼承任何類的話,自己就是基類

Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.” 摘錄來自: Apple Inc. “The Swift Programming Language (Swift 5.0)?!?Apple Books. https://books.apple.com/us/book/the-swift-programming-language-swift-5-0/id881256329

但是在swift中有個隱藏的基類,看如下代碼:

class Person{}
// 輸出:Optional(Swift._SwiftObject)
print(class_getSuperclass(Person.self))

可以看出就算沒有繼承任何類,他還是有父類的。所有的swift類都有個隱藏的基類:Swift._SwiftObject
Swift._SwiftObject文件在 swift源碼可以找到:https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftObject.h

image.png

大致搞懂了X.self是什么東西,再來說下X.Type
X.self 也是有自己的類型的,就是X.Type,就是元類型的類型

class Person {}
class Student : Person {}
var pType = Person.self // pType的類型就是Person.Type
var stuType: Studentp.Type  = Student.self // stuType的類型就是 Studentp.Type
pType = Student.self // 因?yàn)樽宇?,所有可以這樣寫

也可以定義一個接收任意類型的變量 AnyObject.Type

var anyType: AnyObject.Type = Perosn.self
anyType = Student.self

AnyClass:就是 AnyObject.Type的別名
public typealias AnyClass = AnyObject.Type
ok現(xiàn)在AnyObject 也搞清楚了

應(yīng)用

這個東西有什么用呢?舉個簡單的例子

class Animal: NSObject {
    // 必須是 required 保證子類調(diào)用init的時(shí)候初始化成功
    required override init() {
        super.init()
    }

}
class Dog: Animal { }

class Cat: Animal { }

class Pig: Animal { }

func create(_ classes:[Animal.Type]) -> [Animal] {
        var arr = [Animal]()
        for cls in classes {
            arr.append(cls.init())
        }
        return arr
}
create([Dog.self, Cat.self, Pig.self])

Self

1、Self代表當(dāng)前類型

class Person {
    var age = 10
    static var count = 2
    func test() {
        print(self.age)
        // 訪問count的時(shí)候,一般通過類名直接訪問
        print(Person.count)
        // 也可以使用 Self 訪問
        print(Self.count)
    }
}

2、一般作為函數(shù)的返回值使用,限定返回值跟調(diào)用者必須類型一致

protocol Runable {
    func test() -> Self
}

class Person : Runable {
    required init() { }
    func test() -> Self {
        return type(of: self).init()
    }
}

class Student: Person { }

let p = Person().test()
let s = Student().test()
// 輸出:swift___閉包.Person
print(p)
// 輸出:swift___閉包.Student    
rint(s)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容