zoukankan      html  css  js  c++  java
  • 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 中实现就相当于重写的效果。

    题外话

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

  • 相关阅读:
    值不丢失,虽然仅在局部函数中存在
    js 中和c类似
    天天QA
    request methods Hypertext Transfer Protocol (HTTP/1.1)
    单元测试
    access variables from the global scope 在全局范围内访问变量的2种方法
    summary
    安全跟效率之间的折中而已 记住一个大原则,安全和效率是对立的
    微信商城 Common Log Format Apache CustomLog
    僵尸进程 zombie
  • 原文地址:https://www.cnblogs.com/shsuper/p/15640065.html
Copyright © 2011-2022 走看看