【问题标题】:How to override function in extensions for inherited classes?如何覆盖继承类的扩展中的函数?
【发布时间】:2018-02-28 23:52:09
【问题描述】:

我有一个用于UIScrollViewUITableViewscrollToBottom 函数。问题是它们相互冲突并出现错误:Declarations in extensions cannot override yet

这就是我所拥有的:

extension UIScrollView {

    func scrollToBottom(animated: Bool = true) {
        ...
    }
}

extension UITableView {

    func scrollToBottom(animated: Bool = true) {
        ...
    }
}

由于UITableView 继承自UIScrollView,因此不允许我这样做。我怎样才能做到这一点?

【问题讨论】:

    标签: swift extension-methods


    【解决方案1】:

    创建一个协议ScrollableToBottom 并在那里定义你的方法:

    protocol ScrollableToBottom {
        func scrollToBottom(animated: Bool)
    }
    

    使UIScrollViewUITableView 继承自它:

    extension UIScrollView: ScrollableToBottom  { }
    extension UITableView: ScrollableToBottom  { }
    

    那么你只需要将你的协议约束Self扩展到特定的类:

    extension ScrollableToBottom where Self: UIScrollView {
        func scrollToBottom(animated: Bool = true) {
    
        }
    }
    extension ScrollableToBottom where Self: UITableView {
        func scrollToBottom(animated: Bool = true) {
    
        }
    }
    

    【讨论】:

    • 清晰优雅的工作方式!顺便说一句,不需要冗余的 tableview 协议一致性。谢谢!
    • 是的,但如果您还需要在 CollectionView 中实现此方法,则需要这样做
    【解决方案2】:

    您可以使用带有默认实现的协议扩展

    protocol CanScrollBottom {
        func scrollToBottom()
    }
    
    extension CanScrollBottom where Self: UIScrollView {
        func scrollToBottom() {
            //default implementation
        }
    }
    
    extension UIScrollView: CanScrollBottom { }
    
    extension UITableView {
        func scrollToBottom() {
            //override default implementation
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      相关资源
      最近更新 更多