TruMan1
TruMan1

Reputation: 36098

How to override function in extensions for inherited classes?

I have a scrollToBottom function for UIScrollView and UITableView. The problem is they are conflicting with each other with the error: Declarations in extensions cannot override yet

This is what I have:

extension UIScrollView {

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

extension UITableView {

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

Since UITableView inherits from UIScrollView, it's not allowing me to do this. How can I accomplish this?

Upvotes: 0

Views: 332

Answers (2)

Tomasz Pikć
Tomasz Pikć

Reputation: 763

You can use protocol extension with default implementation

protocol CanScrollBottom {
    func scrollToBottom()
}

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

extension UIScrollView: CanScrollBottom { }

extension UITableView {
    func scrollToBottom() {
        //override default implementation
    }
}

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236360

Create a protocol ScrollableToBottom and define your method there:

protocol ScrollableToBottom {
    func scrollToBottom(animated: Bool)
}

Make UIScrollView and UITableView inherit from it:

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

Then you just need to extend your protocol constraining Self to the specific class:

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

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

    }
}

Upvotes: 1

Related Questions