N
N
norlin2016-02-09 12:36:32
Swift
norlin, 2016-02-09 12:36:32

How to add the same method to several classes at once?

I need to add the same method to several classes at once:

class FilterableTable: UITableViewController { ... }
class FilterableCollection: UICollectionViewController { ... }

extension FilterableTable, FilterableCollection { // я знаю, что эта строка некорректна
  func filterItems(){ print('filtered!') }
}

var myTable = FilterableTable()
myTable.filterItems()

var myCollection = FilterableCollection()
myCollection.filterItems()

An extension, as far as I know, cannot be applied to several classes at once.
The protocol only allows you to define method signatures, not the methods themselves.
There is an option with creating a protocol and then extending to it, with a method body. The option seems to be correct, but XCode constantly crashes on it.
The most correct option would be through inheritance, but I can’t figure out how to do this, given that there is no inheritance from several classes in Swift.
I will be grateful for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
norlin, 2016-02-10
@norlin

Finally found an option that looks the most correct: the banal use of delegates.

class FilterableTable: UITableViewController {
    var filterDelegate: FilterDelegate! 
    func viewDidLoad(){
        filterDelegate = Filter()
    }
}
class FilterableCollection: UICollectionViewController {
    var filterDelegate: FilterDelegate! 
    func viewDidLoad(){
        filterDelegate = Filter()
    }
}

protocol FilterDelegate {
    func filterItems()
}

class Filter: FilterDelegate {
    func filterItems() {
        print("Hooray!")
    }
}

A
An, 2016-02-09
@Flanker_4

You didn't do it right. One of those stories where nails are driven in with a microscope. It turns out that all UIViewControllers will have a filterItems method, about which they will not know anything at all. Correct decision
Announce your protocol

protocol <Name> {
   func filterItems()
}

Implementation for the protocol
extension <Name>  {
   func filterItems(){ print('filtered!') }
}

Well, further in the classes you standardly specify protocol support.
From the bad, your view controller does not do what it should do

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question