Giovanni Azua Giovanni Azua - 6 months ago 77
iOS Question

Swift: How to do partial class implementation of a protocol (interface)?

Coming from languages like Java/C++ we are used to partial or abstract class implementations e.g.

protocol ProtocolA {
func x()
func y()
}

// attempt to partially implement ProtocolA
class AbstractProtocolA: ProtocolA {
func x() { /* implementation */ }

// does not implement function y
}

class ConcreteA1: AbstractProtocolA {
func y() { /* implementation */ }
}

class ConcreteA2: AbstractProtocolA {
override func x() { /* implementation */ }
func y() { /* implementation */ }
}


but this is not possible in Swift, in this case I would get the compilation error
Type 'AbstractProtocolA' does not conform to protocol 'ProtocolA'
... is there another Swifty way to cover this OOD use-case?

UPDATE:
A way to circumvent this limitation would be to:

enum ProtocolAError: ErrorType {
case NotImplementedException(methodName: String)
}

class AbstractProtocolA: ProtocolA {
func x() { /* implementation */ }

func y() { throw ProtocolAError.NotImplementedException(methodName: "y") }
}


but here we shift design/programming mistakes (i.e. instantiating the abstract AbstractProtocolA) to runtime rather than compile time.

Answer

You can create a default implementation of the protocol with a protocol extension:

protocol ProtocolA {
   func x()
   func y()
}

extension ProtocolA {
   func x() {
      // Do something (or nothing) here as a default implementation
   }
}

Hope it works ;)

PS: have a look to protocol oriented programming in swift, here are some links: https://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-2 https://developer.apple.com/videos/play/wwdc2015/408/

Comments