协议

协议(Protocal)

  • 协议可以用来定义方法、属性、下标的声明,协议可以被枚举、结构体、类遵守(多个协议之间用逗号隔开)
  • 协议中定义方法时不能有默认参数值
  • 默认情况下,协议中定义的内容必须全部都实现
    • 可以通过关键字做到部分实现
protocol Drawble {
    init(x: Int, y: Int)
     mutating func draw()
    var x: Int { get set }
    var y: Int { get }
    subscript(index: Int) -> Int { get set }
}
final class Size : Drawble {
    init(x: Int, y: Int) {
    }
}

class Person: Drawble {
    required init(x: Int, y: Int) {
    }
//    var x: Int = 0
//    var y: Int = 0
    var width: Int = 0
    var x: Int {
        get { 0 }
        set { }
    }
    var y: Int { 0 }
    func draw() {
        width = 10
        print("Person draw")
    }
    subscript(index: Int) -> Int {
        set { }
        get { index }
    }
}

struct Point: Drawble {
    init(x: Int, y: Int) {
    }
    
    
    var z: Int = 0
    var x: Int {
        get { 0 }
        set { }
    }
    var y: Int { 0 }
    // 结构体中 必须加 mutating 关键字
    mutating func draw() {
        z = 10
    }
    subscript(index: Int) -> Int {
        set { }
        get { index }
    }
}

协议中的属性

  • 协议中定义属性时必须用var关键字
  • 实现协议时的属性权限要不小于协议中定义的属性权限
    • 协议定义get、set,用var存储属性或get、set计算属性去实现
    • 协议定义get,用任何属性都可以实现

staic class

为了保证通用, 协议中必须用static定义类型方法、类型属性、类型下标

mutating

只有将协议中的实例方法标记为mutating

  • 才允许结构体、枚举的具体实现修改自身内容
  • 类的实现方法时不用加mutating,枚举、结构体才需要加mutating

init

  • 协议中还可以定义初始化器 init
  • 非final类实现时必须加上required
  • 如果从协议实现的初始化器,刚好重写了父类的指定初始化器那么这个初始化器必须同时加上 required、override

init init? init!

  • 协议中定义的 init? 、init!, 可以用 init 、init?、init! 去实现
  • 协议中定义的 init, 可以用 init、init!去实现
protocol Livable {
    init()
    init?(age: Int)
    init!(no: Int)
}
class Person: Livable {
    required init() { }
    // required init!() { }
    required init?(age: Int) { }
    // required init!(age: Int) { }
    // required init(age: Int) { }
    required init!(no: Int) { }
    // required init?(no: Int) { }
    // required init(no: Int) { }
    }

协议的继承

一个协议可以继承其他协议

protocol Runnable {
    func run()
}
protocol Livable: Runnable {
    func breath()
}
class Person: Livable {
    func breath() {
            
    }
    func run() {
        
    }
}

协议组合

  • 协议组合 可以包含一个类类型(最多一个)
protocol Runnable { }
protocol Livable { }
class Person { }
// 接收 Person 或者 其子类的实例
func fn0(obj: Person) { }
// 接收 遵守 Livable 协议的实例
func fn1(obj: Livable) { }
// 接收同时遵守 Runnable、Livable 协议的实例
func fn2(obj: Runnable & Livable) { }
// 接收同时遵守 Runnable、Livable 协议,并且是 Person 或者其子类的实例
func fn3(obj: Person & Livable & Runnable) { }

CaseIterable

让枚举遵守 CaseIterable 协议,可以实现遍历枚举值

enum Season: CaseIterable {
    case apring, summer, autumn, winter
}
let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
    print(season)
}
// apring, summer, autumn, winter

CustomStringConvertible CustomDebugStringConvertible

遵守 CustomStringConvertible、CustomDebugStringConvertible 协议,可以实现自定义实例的打印字符串

class Person : CustomStringConvertible, CustomDebugStringConvertible {
    var age : Int = 0
    var description: String {
        "age= \(age)"
    }
    var debugDescription: String {
        "debug_person_\(age)"
    }
}
var p = Person()
print(p) // age= 0
debugPrint(p) // debug_person_0

Any AnyObject

  • Any : 可以代表任意类型(枚举、结构体、类、也包括函数类型)
  • AnyObject :可以代表任意类类型(在协议后面写上:AnyObject 代表只有类能遵守这个协议)
// 创建一个能存放任意类型的数组
var data = [Any]()
var datas = Array<Any>()

is as? as! as

is 用来判断是否为某种类型, as 用来做强制类型转换

protocol Runnable { func run() }
class Person { }
class Student: Person, Runnable {
    func run() {
        print("Student run")
    }
    func study() {
        print("Student study")
    }
}
var stu: Any = 10
print(stu is Int) // true
stu = "Jack"
print(stu is String) // true
stu = Student()
print( stu is Person) // true
print( stu is Student) // true
print( stu is Runnable) // true

var stu1: Any = 10
(stu1 as? Student)?.study() // 没有调用study
stu1 = Student()
(stu1 as? Student)?.study() // Student study
(stu1 as! Student).study() // Student study
(stu1 as? Student)?.run() // Student run

var data = [Any]()
data.append(Int("123") as Any)

X.self X.Type AnyClass

  • X.self 是一个元类型(metadata)的指针,metadata 存放着类型相关的信息
  • X.self 属于 X.Type类型
class Person { }
class Student : Person { }

var p = Person()

Person.self
// 8个字节放的是metedata的地址值就是 实例变量p的前8个字节
// 是Person.Type类型
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self

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

public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self

perType = type(of: p)
print(Person.self == type(of: p)) // true

/*
汇编分析
register read rax
     rax = 0x0000000100014e48  type metadata for Person #1 in swiftstudy.test36() -> ()
(lldb) register read rax
     rax = 0x0000000102900000
(lldb) x/5wg 0x0000000102900000
0x102900000: 0x0000000100014e48 0x0000000000000002
0x102900010: 0x0000000000000000 0x0000000000000000
0x102900020: 0x2f6d657473790017
*/
// 可以看出来, Swift 还有个隐藏的基类:Swift.__SwiftObject,其实他和 oc 一样,前8个字节存的也是 isa 指针(就是用于查找他的类信息的),其实也可以理解,打印所有的纯 swift 对象,可以发现一个规律,就是前8个字节存储 isa,后面跟着8个字节存储引用计数,把他们抽成一个父类其实更合理。

  • 元类的应用
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]))

class Person {
    var age: Int = 10
}
class Student: Person {
    var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Student.self)!) // Person
print(class_getSuperclass(Person.self)!) // _TtCs12_SwiftObject

Self

  • Self 一般用作返回值类型,限定返回值方法调用者必须是同一类型(也可以作为参数类型)
  • 如果 Self 用在类中,要求返回时调用的初始化是 required 的
  • 一般如果我想链式调用的话,会这样写
class Person {
    required init() {
    }
    func test() -> Self {
        Self.self.init()
    }
    func test1() -> Self {
        Self.self.init()
    }
}

class Student: Person {
}
let p = Person().test().test1()
  • Self 代表当前类型
class Person {
    var age = 1
    static var count = 2
    func run() {
        print(self.age) // 1
        print(Self.count) // 2 Self 代表当前类型
    }
}

思考

  1. type(of: p) == Person.self? type(of: p) 和 sizeof 这种是一样的,本质不是调用函数,只是将 p 的前8个字节取出来,所以 type(of: p)和 Person.self 是相等的
  2. Person 和 Person.self 的异同
class Person {
    static var age = 0
    static func run() {}
}

Person.age = 10
Person.self.age = 20

func test(_ cls: AnyClass) {
    
}
test(Person.self)

也就是说当你明确需要传 X.Type 的时候,这个时候X.self,不然用类名一般就够用了

posted @ 2021-04-22 15:30  YALMiOS  阅读(102)  评论(0)    收藏  举报