A way to inherit from multiple classes

给你一囗甜甜゛ 提交于 2020-01-01 17:03:57

问题


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 {
}

Since Swift doesn't allow a class to inherit from multiple classes the following example obviously won't work:

class ItemViewCell: DeleteItem, OpenDetail {
}

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 {
}

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?


回答1:


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)
}

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++
  }
}

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.



来源:https://stackoverflow.com/questions/35058079/a-way-to-inherit-from-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!