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 中实现就相当于重写的效果。

题外话

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我为双鱼狂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值