norlin February 2016

How can I add the same methods to different classes?

Is it possible to add the same methods to different classes?

Example:

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

extension FilterableTable, FilterableCollection { // I know this line is wrong
  func filterItems(){ print('filtered!') }
}

How can I add the same Foo method to a UICollectionViewController?

Protocols allow to declare only needed methods signatures, but I need exactly the same method (with body), to avoid copy-paste...

Answers


Mr Beardsley February 2016

You can use the Protocol Extensions to do what you need. Extensions are new and allow for a default implementation of the protocol methods. I modified your code just a bit so it would compile.

class FilterableTable: FilterType { 
    init() {}
}
class FilterableCollection: FilterType {  
    init() {}
}

protocol FilterType {
    func filterItems()
}
extension FilterType { // I know this line is wrong
  func filterItems(){ print("filtered!") }
}

let a = FilterableTable()
a.filterItems()

let b = FilterableCollection()
b.filterItems()

Check out the section on Protocol Extensions. Swift Programming Guide


norlin February 2016

Actual answer: Use the Delegates, Luke!

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

Post Status

Asked in February 2016
Viewed 3,053 times
Voted 5
Answered 2 times

Search




Leave an answer