一种从多个类继承的方法 [英] A way to inherit from multiple classes
问题描述
我想在我的新课程中使用两个课程。第一个实现滑动删除,第二个实现长按手势:
I have two classes I want to use in my new class. The first one implements a swipe to delete and the second enables a long press gesture:
class DeleteItem: UITableViewCell {
}
class OpenDetail: UITableViewCell {
}
自Swift不允许类继承多个类,以下示例显然不起作用:
Since Swift doesn't allow a class to inherit from multiple classes the following example obviously won't work:
class ItemViewCell: DeleteItem, OpenDetail {
}
所以为了创建 ItemViewCell
并且有两个选项,我必须让其中一个类继承彼此:
So in order to create ItemViewCell
and having both options, I'll have to have one of the classes to inherit from each other:
class DeleteItem: UITableViewCell {
}
class OpenDetail: DeleteItem {
}
class ItemViewCell: OpenDetail {
}
问题是,如果我只想要长按手势,我将不得不创建一个新类而不继承 DeleteItem
。有没有更好的方法呢?
The problem is, if I only want the long press gesture I'll have to create a new class without inheriting from DeleteItem
. Is there a better way of doing this?
推荐答案
这是使用协议和协议扩展的完美案例。 swift 协议
就像Java中的接口一样。协议可以定义一组功能,这些功能必须由想要符合该协议的实体来实现,而且协议也可以定义必须存在于这些实体中的属性。例如:
This is the perfect case for using Protocols and Protocol extension. A swift protocol
is like an interface in Java for example. A protocol can define a set of functions which has to be implemented by the entities which want to conform to this protocol, moreover a protocol can define properties which has to be present in these entities too. For example:
protocol ItemDeleter {
var deletedCount: Int {get set}
func deleteItem(item: ItemType)
}
问题是,每个实体都必须提供自己的实现 func deleteItem(item:ItemType)
即使多个实体共享相同的删除项目逻辑,协议扩展也会派上用场。例如:
The problem is, that each entity would have to provide its own implementation of func deleteItem(item: ItemType)
even if multiple entities share the same logic of deleting an item, this where a protocol extension comes in handy. For example:
extension ItemDeleter {
func deleteItem(item: ItemType) {
// logic needed to delete an item
// maybe incremented deletedCount too
deletedCount++
}
}
然后你可以让你的 ItemViewCell
符合 ItemDeleter
协议,在这种情况下,您只需要确保 ItemViewCell
具有属性 deletedCount:Int
。它不需要为 func deleteItem(item:ItemType)
提供实现,因为协议本身提供了此函数的默认实现,但是您可以在类中覆盖它,并将使用新的实施。这同样适用于 DetailOpener协议
。
Then you could make your ItemViewCell
conform to the ItemDeleter
protocol, in this case all you need is to make sure that ItemViewCell
has a property deletedCount: Int
. It does not need to provide an implementation for func deleteItem(item: ItemType)
as the protocol itself provides a default implementation for this function, however you can override it in your class, and the new implementation will be used. The same applies for DetailOpener protocol
.
这篇关于一种从多个类继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!