Swift-协议(Protocol)

97 阅读5分钟

协议

  • 协议可以用来定义方法、属性、下标的声明,协议可以被枚举,结构体、类遵守(多个协议之间用逗号隔开)
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关键字(实现有时候需要更改的,你用let 就修改不了)
  • 实现协议时的属性权限要不小于协议中定义的属性权限
  • 协议定义get、set 用var存储属性或get、set计算属性去实现
  • 协议定义get,用任何属性都可以实现(常量或者就算属性的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
    // 只读
    let y:Int = 0
    func draw(){
        print("Person draw")
    }
    subscript(index:Int) -> Int {
        set {}
        get {index}
    }
}
class Person:Drawable {
    // 可读可写
    var x:Int {
        get {0}
        set {}
    }
    var y:Int {0} // 只读
    func draw(){print("Person draw")}
     subscript(index:Int) -> Int {
        set {}
        get {index}
    }
}

static、class

  • 为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标
protocol Drawable {
    static func draw()
}
class Person1:Drawable {
    class func draw(){
        print("Person1 draw")
    }
}
class Person2:Drawable {
    static func draw(){
        print("Person2 draw")
    }
}

mutating

  • 只有将协议中的实例方法标记为mutating
  • 才允许结构体、枚举的具体实现修改自身内存
  • 类在实现方法时不用加mutating,枚举、结构体才需要加mutating
protocol Drawable {
    mutating func draw()
}
class Size:Drawable {
    var width:Int = 0
    func draw(){
        width = 10
    }
}
class Point:Drawable {
    var x:Int = 0
    //在协议中去掉mutating,然后在Point 方法中加上行不行,不行
    mutating func draw(){
        x = 10
    }
}

init

  • 协议中还可以定义初始化器init
  • 非final类实现时必须加上required(不允许被继承)
为了保证所有遵守Drawable协议的类和子类,都去实现,必须定义成required
protocol Drawable {
    init(x:Int,y:Int)
}
class Point:Drawable {
    required init(x:Int,y:Int)
}
final class Size:Drawable{ //final 不能被子类继承
   init(x:Int,y:Int)
}
  • 如果从协议实现的初始化器,刚好是重写了父类的指定初始化器
  • 那么这个初始化必须同时加required、override
protocol Livable {
    init(age:Int)
}
class Person {
    init(age:Int){} 
}
class Student:Person,Livable {
    // override 是重写了父类的,required 是遵守了协议,必须加上requird
    required override init(age:Int){
        super.init(age:age)
    }
}

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(){}
}

协议组合

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

protocol Livable {}
protocol Runnable {}
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

  • 遵守CustomStringConvertible协议,可以自定义实例的打印字符串
class Person :CustomStringConvertible {
    var age:Int
    var name:String
    init(age:Int,name:String){
        self.age = age
        self.name = name
    }
    var description:String {
        "age=\(age),name=\(name)"
    }
}
var p = Person(age:10,name:"Jack")
print(p) // age=10,name=Jack

Any、AnyObject

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

//创建1个能存放任意类型的数组
// var data = Array<Any>()
var data = [Any]()
data.append(1)
data.append(3.14)
data.append(Student())
data.append("Jack")
data.append({10})
protocol Runnable:AnyObject {}
class Person:Runnable{}
struct Size:Runnable{}

报错:error: MyPlayground.playground:7:8: error: non-class type 'Size' cannot conform to class protocol 'Runnable'

struct Size:Runnable{}

^

image.png

is、as?、as!、as

  • is 用来判断是否为某种类型,as用来做强制类型转换
protocol Runable {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
/*
as? 转换可能成功,可能失败,结果是可选类型,那么在调用可选链时要加入?
as!转换的时候强制解包
*/


var stu:Any = 10
(stu as? Student)?.study() // 没有调用study
stu = Student()
(stu as? Student)?.study() // Student study
(stu as! Student).study() // Student study 强制转换
(stu as? Runnable)?.run() // Student run
var data = [Any]()
data.append(Int("123") as Any)

var d = 10 as Double
print(d) // 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
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 per = Person()
var perType = type(of:per) // Person.self
print(Person.self == type(of:per)) // true

5种创建方式都是一样的

class Person{
    static var age = 0
    static func run(){}
}

Person.age = 10 // 等价于Person.self.age = 10
Person.run() //等价于 Person.self.run()

var p0 = Person()
var p1 = Person.init()
var p2 = person.self()
var p3 = Person.self.init()
var p4 = type(of p0).init()

元类型的应用

相当于OC中的class,根据class 生成 对象

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 = 0
}
class Student:Person {
    var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Studentn.self)!) //Person
print(class_getSuperclass(Person.self)!) //Swift._SwiftObject

Self(限定返回值类型,类似OC instancetype)

  • Self代表当前类型
class Person {
    var age = 1
    static var count = 2
    func run() {
        print(self.age) //1 小写self访问实例属性,方法
        print(Self.count) // 2 大写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())

如果Self用在类中,要求返回时调用的初始化器是required的(是保证子类也能够准确的调用构造器,required 要求子类必须实现)