我有scrollToBottom
和UIScrollView
的UITableView
功能。问题是它们之间存在错误:Declarations in extensions cannot override yet
这就是我所拥有的:
extension UIScrollView {
func scrollToBottom(animated: Bool = true) {
...
}
}
extension UITableView {
func scrollToBottom(animated: Bool = true) {
...
}
}
由于UITableView
继承自UIScrollView
,它不允许我这样做。我怎么能做到这一点?
创建协议ScrollableToBottom
并在那里定义您的方法:
protocol ScrollableToBottom {
func scrollToBottom(animated: Bool)
}
让UIScrollView
和UITableView
继承它:
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) {
}
}
您可以使用默认实现的协议扩展
protocol CanScrollBottom {
func scrollToBottom()
}
extension CanScrollBottom where Self: UIScrollView {
func scrollToBottom() {
//default implementation
}
}
extension UIScrollView: CanScrollBottom { }
extension UITableView {
func scrollToBottom() {
//override default implementation
}
}