swift - How can I add the same methods to different classes? -
is possible add same methods different classes?
example:
class filterabletable: uitableviewcontroller { ... } class filterablecollection: uicollectionviewcontroller { ... } extension filterabletable, filterablecollection { // know line wrong func filteritems(){ print('filtered!') } }
how can add same foo method uicollectionviewcontroller
?
protocols allow declare needed methods signatures, need same method (with body), avoid copy-paste...
you can use protocol extensions need. extensions new , allow default implementation of protocol methods. modified code bit compile.
class filterabletable: filtertype { init() {} } class filterablecollection: filtertype { init() {} } protocol filtertype { func filteritems() } extension filtertype { // know line wrong func filteritems(){ print("filtered!") } } let = filterabletable() a.filteritems() let b = filterablecollection() b.filteritems()
check out section on protocol extensions. swift programming guide
Comments
Post a Comment