如何覆盖继承类的扩展中的函数?

问题描述 投票:0回答:2

我有scrollToBottomUIScrollViewUITableView功能。问题是它们之间存在错误: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
2个回答
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) {

    }
}

1
投票

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

protocol CanScrollBottom {
    func scrollToBottom()
}

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

extension UIScrollView: CanScrollBottom { }

extension UITableView {
    func scrollToBottom() {
        //override default implementation
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.