美文网首页iOS 底层面试待处理
Swift-通过协议的方式为某个类扩展一个属性

Swift-通过协议的方式为某个类扩展一个属性

作者: Lxyang | 来源:发表于2020-12-27 23:55 被阅读0次

    本例中,1、我们展示的是为UIView扩展一个sd属性。sd属性是SDAutoLayout类型。2、为UIView添加一个静态sd属性,可示自定义静态方法或属性


    1、声明协议,并为协议提供默认实现,添加sd属性。

    /** --------------------------------------------
     * 为UIView扩展一个sd添加属性,然后再提供一个默认layout()函数,返回的是SDAutoLayoutModel类
     * 方便链式调用
     * 防止UIView中有layout方法,然后重名
     * -----------------------------------------------
     */
    
    public protocol SDAutoLayoutCompatible {
        /// associatedtype关键字用来指定关联类型
        associatedtype T
        /// 添加一个为只读的关联属性:sd
        var sd: T { get }
    }
    
    /// 协议扩展,可提供默认实现,返回一个SDAutoLayout类型对象。
    extension SDAutoLayoutCompatible {
        // sd:关联SDAutoLayout类型的属性 默认实现
        public var sd: SDAutoLayout<Self> {
            get {
                return SDAutoLayout.init(self)
            }
        }
    }
    

    扩展属性的类型,一般为一个class类。
    上面协议所扩展一个sd属性,其类型为SDAutoLayout

    /// 声明一个类,为此类扩展并指定类型
    public final class SDAutoLayout<Base> {
        public let base: Base
        public init(_ base: Base) {
            self.base = base
        }
    }
    
    /// 扩展SDAutoLayout,并指定类型为UIView, 为其添加一个layout()方法
    // 为UIView扩展的sd添加方法
    extension SDAutoLayout where Base: UIView {
        /// 可通过UIView().sd.layout().leftSpace来调用。防止layout方法重名
        @discardableResult // 未使用的返回值警告消除
        func layout() -> SDAutoLayoutModel {
            return base.sd_layout()
        }
    }
    

    UIView扩展实现SDAutoLayoutCompatible,那么它就拥有了sd属性

    /// 为UIView添加一个扩展,并实现协议,让它有sd关联属性,默认为SDAutoLayout类型
    extension UIView: SDAutoLayoutCompatible {}
    

    2、为类或结构体添加静态属性、成员属性

    /** --------------------------------------------
     * 为UIView扩展一个sd属性,一个sd静态属性,
     * 方便链式调用
     * 防止UIView中有layout方法,然后重名
     * -----------------------------------------------
     */
    public protocol SDAutoLayoutCompatible {}
    
    /// 协议扩展,可提供默认实现,返回一个SDAutoLayout类型对象。
    extension SDAutoLayoutCompatible {
        // sd:关联SDAutoLayout类型的属性 默认实现
        public var sd: SDAutoLayout<Self> {
            get {
                return SDAutoLayout.init(self)
            }
        }
        // 静态属性
        public static var sd: SDAutoLayout<Self>.Type {
            get {
                return SDAutoLayout<Self>.self
            }
        }
    }
    
    /// 声明一个结构体,为此类扩展并指定类型
    public struct SDAutoLayout<Base> {
        public let base: Base
        public init(_ base: Base) {
            self.base = base
        }
    }
    
    /// 扩展SDAutoLayout,并指定类型为UIView, 为其添加一个layout属性, 静态方法或静态属性
    // 要扩展sd属性的方法或属性都在这里实现即可
    extension SDAutoLayout where Base: UIView {
     
        /// 可通过UIView().sd.layout.leftSpace来调用。防止layout方法重名
        var layout: SDAutoLayoutModel {
            get {
                return base.sd_layout()
            }
        }
        
        /// 静态方法
        @discardableResult // 未使用的返回值警告消除
        public static func getView() -> UIView {
            DXLog(message: "通过sd静态属性调用方法UIView.init: \(Base.init())")
            return Base.init()
        }
        
        /// 默认背景颜色
        static var defaultBgColor: UIColor {
            get {
                return UIColor.green
            }
        }
    }
    
    /// 为UIView添加一个扩展,并实现协议,让它有sd关联属性,默认为SDAutoLayout类型
    extension UIView: SDAutoLayoutCompatible {}
    

    3、使用

    静态属性的使用
    let view = UIView.sd.getView()
    self.view.backgroundColor = UIView.sd.defaultBgColor
    
    实例属性的使用
    imageView!.sd.layout().leftTo(contentView, 10)
                .topTo(contentView, 10)
                .width(is: 70).height(is: 100)
    textLabel!.sd.layout().centerYEqualTo(contentView)
                .leftTo(imageView!, 10)
                .rightTo(contentView, 10)
                .autoHeight(0)// 高度自适配
    

    4、 swift中Self 、.self 、.Type是什么

    • Self关键字
      • swfit5.1开始, 可用Self替代类名来访问静态成员
      class ListViewController: UITableViewController {
        static let cellReuseIdentifier = "list-cell-identifier"
      
        override func viewDidLoad() {
          super.viewDidLoad()
      
          tableView.register(
              ListTableViewCell.self,
              forCellReuseIdentifier: Self.cellReuseIdentifier
          )
        }
      }
      
      • Self在未知具体类型的上下文中动态引用实际上的类型,例如,通过在协议扩展中引用协议的具体实现类型
      extension Numeric {
        func incremented(by value: Self = 1) -> Self {
            return self + value
        }
      }
      给Numeric协议扩展了一个自增的方法,
      但是我们现在不知道具体自增的类型,使用Self作为返回类型,则可以动态获取对应的类型:
      let num1 = 5.incremented()           //num1: Int
      let num2 = 5.0.incremented()         //num2: Double
      
    • .Type关键字
      Swift 中的元类型用 .Type 表示。比如 Int.Type 就是 Int 的元类型。
      类型与值有着不同的形式,就像 Int 与 5 的关系。元类型也是类似,.Type 是类型,类型的 .self 是元类型的值。

    相关文章

      网友评论

        本文标题:Swift-通过协议的方式为某个类扩展一个属性

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