12-协议

作者: SwordDevil | 来源:发表于2021-08-05 08:14 被阅读0次

协议(Protocol)

协议中的属性

static、class

mutating

init

init、init?、init!

协议的继承

协议组合

CaseIterable 遍历枚举

CustomStringConvertible

补充
  • 遵守CustomStringConvertible、CustomDebugStringConvertible协议,都可以自定义实例的打印字符串
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
  • print调用的是CustomStringConvertible协议的description
  • debugPrint、po调用的是CustomDebugStringConvertible协议的debugDescription

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

  • 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())

相关文章

网友评论

      本文标题:12-协议

      本文链接:https://www.haomeiwen.com/subject/glrjvltx.html