Laap
Laap

Reputation: 71

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

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?

Upvotes: 2

Views: 4298

Answers (1)

ysholqamy
ysholqamy

Reputation: 221

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.

Upvotes: 4

Related Questions