Swift - 协议(Protocol)

协议(Protocol)

  • 协议可以用来定义 方法属性下标 的声明,协议可以被 枚举结构体 遵守(多个协议之间用逗号隔开)
protocol Drawable {
    func draw()
    var x: Int { get set }
    var y: Int { get }
    subscript(index: Int) -> Int { get set }
}

protocol Test1 { }
protocol Test2 { }
protocol Test3 { }
class TestClass: Test1, Test2, Test3 { }
  • 协议中定义方法时不能有默认参数值

协议中的属性

  • 协议中定义属性时必须用 var 关键字
  • 实现协议时的属性权限要 不小于 协议中定义的属性权限
  • 协议定义 getset,用 var 存储属性或 getset 计算属性去实现
  • 协议定义 get,用任何属性都可以实现
protocol Drawable {
    func draw()
    var x: Int { get set }
    var y: Int { get }
    subscript(index: Int) -> Int { get set }
}
class Person: Drawable {
    var x: Int = 0
    var y: Int = 0
    func draw() {
        print("Person draw")
    }
    subscript(index: Int) -> Int {
        set {}
        get { index }
    }
}
class Person: Drawable {
    var x: Int {
        set {}
        get { 0 }
    }
    var y: Int { 0 }
    func draw() {
        print("Person draw")
    }
    subscript(index: Int) -> Int {
        set {}
        get { index }
    }
}

static、class

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

protocol Drawable {
    static func draw()
    static func drift()
}

class Person: Drawable {
    class func draw() {
        print("Person draw")
    }
    static func drift() {
        print("Person drift")
    }
}

mutating

  • 只有将协议中的实例方法标记为 mutating
    • 才允许结构体、枚举的具体实现修改自身内存
    • 类在实现方法时不用mutating,枚举、结构体才需要mutating
protocol Drawable {
    mutating func draw()
}

class Size: Drawable {
    var width: Int = 0
    func draw() {
        width = 10
    }
}

struct Point: Drawable {
    var x: Int = 0
    mutating func draw() {
        x = 10
    }
}

init

  • 协议中还可以定义初始化器 init
    • final 类实现时必须加上 required
protocol Drawable {
    init(x: Int, y: Int)
}

class Point: Drawable {
    required init(x: Int, y: Int) { }
}

final class Size: Drawable {
    init(x: Int, y: Int) { }
}
  • 如果从协议实现的初始化器,刚好是重写了父类的指定初始化器
    • 那么这个初始化必须同时加 requiredoverride
protocol Livable {
    init(age: Int)
}

class Person {
    init(age: Int) { }
}

class Student: Person, Livable {
    required override init(age: Int) {
        super.init(age: age)
    }
}

init、init?、init!

  • 协议中定义的 init?init!,可以用 initinit?init! 去实现
  • 协议中定义的 init,可以用 initinit! 去实现
protocol Livable {
    init()
    init?(age: Int)
    init!(name: String)
}

class Person: Livable {
    required init() { }
    // required init!() { }
    
    required init?(age: Int) { }
    // required init!(age: Int) { }
    // required init(age: Int) { }
    
    required init!(name: String) { }
    // required init?(name: String) { }
    // required init(name: String) { }
}

协议的继承

protocol Runnable {
    func run()
}

protocol Livable: Runnable {
    func breath()
}

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

协议组合

协议组合,可以包含 1 个类类型(最多一个

protocol Runnable { }
protocol Livable { }
class Person {}

// 接收 Person 或者其子类的实例
func fn0(obj: Person) { }
// 接收遵守 Livable 协议的实例
func fn1(obj: Livable) { }
// 接收同时遵守 Livable、Runnable 协议的实例
func fn2(obj: Livable & Runnable) { }
// 接收同时遵守 Livable、Runnable 协议、并且是 Person 或者其子类的实例
func fn3(obj: Person & Livable & Runnable) { }

typealias RealPerson = Person & Livable & Runnable
// 接收同时遵守 Livable、Runnable 协议、并且是 Person 或者其子类的实例
func fn4(obj: RealPerson) { }

CaseIterable

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

enum Season: CaseIterable {
    case spring, summer, autumn, winter
}

let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
    print(season)
}
// spring summer autumn winter

CustomStringConvertible

  • 遵守 CustomStringConvertibleCustomDebugStringConvertible 协议,都可以自定义实例的打印字符串
class Person: CustomStringConvertible, CustomDebugStringConvertible {
    var age = 18
    var description: String { "person_\(age)" }
    
    var debugDescription: String { "debug_person_\(age)" }
}

var person = Person()
print(person)  // person_18
debugPrint(person)  // debug_person_18
  • print 调用的是 CustomStringConvertible 协议的 description
  • debugPrintpo(lldb 指令) 调用的是 CustomDebugStringConvertible协议的 debugDescription

Any、AnyObject

  • Swift 提供了 2 种特殊的类型:AnyAnyObject
  • Any:可以代表任意类型枚举、结构体、类、也包括函数类型
  • AnyObject:可以代表任意 类型(在协议后面写上:AnyObject 代表只有类能遵守这个协议)
    • 在协议后面写上 class:也代表只有类能遵守这个协议
var student: Any = 18
student = "Rose"
student = Student()

// 创建一个能存放任意类型的数组
//var data = Array()
var data = [Any]()
data.append(1)
data.append(3.14)
data.append("Rose")
data.append({ 10 })

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 student: Any = 18
(student as? Student)?.study() // 没有调用 study
student = Student()
(student as? Student)?.study() // Student study
(student as! Student).study()  // Student study
(student as? Student)?.run()   // Student run

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

var double = 10 as Double
print(double)  // 10.0

X.self、X.Type、AnyClass

  • X.self 是一个元类型(metadata)的指针,metadata 存放着类型相关信息
  • X.self 属于 X.Type 类型
class Person { }
class Student: Person { }
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
print(perType, stuType)  // Person Student
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

var person = Person()
var personType = type(of: person) // Person.self
print(Person.self == type(of: person)) // true

元类型的应用

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([Cat.self, Dog.self, Pig.self])
class Person {
    var age: Int = 0
}

class Student: Person {
     var name: String = "Rose"
}

print(class_getInstanceSize(Student.self)) // 40
print(class_getSuperclass(Student.self)!)  // Person
print(class_getSuperclass(Person.self)!)   // _TtCs12_SwiftObject

Self

  • Self 代表当前类型
class Person {
    var age = 18
    static var count = 1
    func run() {
        print(self.age)
        print(Self.count)
    }
}
  • Self 一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)
protocol Runnable {
    func test() -> Self
}

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

class Student: Person { }

var p = Person()
print(p.test()) // Person

var stu = Student()
print(stu.test()) // Student

你可能感兴趣的:(Swift - 协议(Protocol))