Swift-技巧十 Protocol 的灵活使用

摘要

Protocol 是 Swift 中实现面向协议编程思想的重要部分。在使用过程中有遇到协议中声明的部分,但是在遵守部分不需要实现的,那么就需要使用 extension 参与进来,让 Protocol 使用的更加灵活,得心应手。

Protocol 是 Swfit 中重要的编程方式,也就是面向协议编程。主要就是为了解决继承过程中造成的多态情况。除此之外,在项目中也常用到代理中。

这里以遵守代理为例,来看一下 Protocol 在使用过程中可能遇到的问题,首先可以创建一个 Protocol 结构。

protocol CustomProtocol {
}

CustomProtocol 结构中可以声明属性或者函数。这里声明一个 name 属性和 running 函数。

protocol CustomProtocol {
    var name: String { get set }
    
    func running()
}

创建一个 Personstruct 类型数据,遵守 CustomProtocol 协议。

struct Person: CustomProtocol {
    
}

这时会报一个编译错误,大致意思就是 Person 结构体没有实现 CustomProtocol 协议中的属性或者方法。

protocol-image1

一般遇到这样的错误,直接点击 Fix ,Xcode 会帮你自动在 Person 中创建,然后你自己去设置一下就可以消除这个编译错误。

struct Person: CustomProtocol {
    var name: String {
        get { "no name"}
        set { }
    }
    func running() {
        print("running until stop")
    }
}

到这一步,就完成了 protocol 的使用操作,但是,如果我还有一个 Person2 的结构体类型也遵守协议,它只有 name 属性,没有 running 函数时,就依然报一个编译错误

protocol-image2

这就太强迫人了,我就想做到想用就用,不想用就不用 running 函数,怎么做?

Swift 给出的方案就是在 protocolextension 中实现它

extension CustomProtocol {
    
    func running() {
        print("running at CustomProtocol")
    }
}

刚刚报的编译错误就消除了。这时,你就可以在 Person2 中想用就用,不想用就不用。

总结

protocol 中声明的属性或者函数,当有 struct 或者 class 遵守时,就必须全部实现 protocol 中的属性或者函数。

若要遵守 protocolstruct 或者 class 自己决定属性或者函数实现与否,就要在 protocolextension 中去先实现这些属性或者函数。之后再在 struct 或者 class 中实现就相当于重写的效果。

题外话

时间仓促,说的东西可能不全面,在你查看的过程中遇到什么问题,评论区给我留言,我会尽快回复

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...