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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -