美文网首页
swift -面向协议编程

swift -面向协议编程

作者: 在知识的海洋里溺水身忘的小不懂 | 来源:发表于2020-05-07 12:46 被阅读0次

    面向协议编程

    介绍

    • 面向协议编程(protocol oriented programming, 简称 POP)
    • 是 swift 的一种范式编程,Apple 于 2015 年 WWDC 提出
    • 在swift 标准库中,能捡到大量 POP 的影子
    • swift 是一门面向对象语言,OOP
    • swift 开发中,OOP 和 POP 相辅相成,不能互相取代
    • POP 弥补 OOP 设计上的不足

    用法

    • 用法: 想使用 obj.CJ.xxx 或 obj.CJ.xxx() 效果

      // 1.使用 .CJ 所声明的前缀类型
      
      struct CJ<Base> {
          var base: Base
          init(_ base: Base) { self.base = base }
      }
      
      // 2.创建一个协议,利用协议拓展前缀属性
      protocol CJCompatible { }
      
      // 3. 扩展协议,实现实例方法和类方法的 get 方法, set 必须写
      extension CJCompatible {
          
          var cj: CJ<Self> {
              get{ CJ(self) }
              set{}
          }
          
          static var cj: CJ<Self>.Type {
              set{}
              get{ CJ<Self>.self }
          }
      }
      
      // 1. 2. 3. 为通用步骤
      
      
      var str = "121212121fdgddgdgdererer589467391"
      
      // 4.遵守 CJCompatible 协议,使 String, NSString 拥有 CJ 前缀
      extension String: CJCompatible { }
      extension NSString: CJCompatible { }
      
      // 实现 ExpressibleByStringLiteral 为 String 和 NSString 共同遵守的协议
      extension CJ where Base: ExpressibleByStringLiteral {
          
          var numberCount: Int {
              // 实例方法 str.cj.numberCount
          }
          
          static func text() {
              // 类调用 String.cj.text()
          }
          
          mutating func insert() {
              /*
                  变量可调用
                  var str = "121212121fdgddgdgdererer589467391"
                  str.cj.insert()
              */
          }
      }
      
      
      // 自定义类扩展协议
      class Person { }
      
      // 遵守协议,拥有 CJ 前缀
      extension Person: CJCompatible { }
      
      // 实现方法
      extension CJ where Base: Person {
          
          func run() {
              // Person 及其子类都能调用
          }
      }
      
      extension CJ where Base == Person {
          
          func run() {
              // 只有 Person 能调用
          }
      }
      
      
      
    • 使用

      protocol ArrayType { } //声明一个协议
      
      // 共同遵守
      extension Array: ArrayType {}    
      extension NSArray: ArrayType {}
      
      // 将类型作为参数判断
      func isArrayType(_ type: Any.Type) -> Bool {
          type is ArrayType.Type
      }
      
      print( isArrayType( [Int].self ))
      print( isArrayType( [Any].self ))
      print( isArrayType( NSArray.self ))
      print( isArrayType( NSMutableArray.self ))
      print( isArrayType( String.self ))
      
      
      /*  打印结果
          true
          true
          true
          true
          false
      */
      

    相关文章

      网友评论

          本文标题:swift -面向协议编程

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