12-协议

2021-08-05  本文已影响0人  SwordDevil

协议(Protocol)

协议中的属性

static、class

mutating

init

init、init?、init!

协议的继承

协议组合

CaseIterable 遍历枚举

CustomStringConvertible

补充
class Person : CustomStringConvertible, CustomDebugStringConvertible {
    var age = 0
    var description: String { "person_\(age)" }
    var debugDescription: String { "debug_person_\(age)" }
}
var person = Person()
print(person) // person_0
debugPrint(person) // debug_person_0

Any、AnyObject

is、as?、as!、 as

X.self、 X.Type、 AnyClass

元类型的应用

class Animal { required init() {} }
class Cat : Animal {}
class Dog : Animal {}
class Pig : Animal {}
func create(_ clses: [Animal.Type]) -> [Animal] {
    var arr = [Animal]()
    for cls in clses {
        arr.append(cls.init())
    }
    return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
import Foundation
class Person {
    var age: Int = 0
}
class Student : Person {
    var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Student.self)!) // Person
print(class_getSuperclass(Person.self)!) // Swift._SwiftObject

Self

protocol Runnable {
func test() -> Self
}
class Person : Runnable {
required init() {}
func test() -> Self { type(of: self).init() }
}
class Student : Person {}

var p = Person()
// Person
print(p.test())
var stu = Student()
// Student
print(stu.test())
上一篇 下一篇

猜你喜欢

热点阅读