swiftprotocolsprotocol-extension

Swift protocol to only implemented by specific classes


I want to create a protocol which is only adopted by a specific class and its subClassses in swift. I know i can use protocol extensions like this

  protocol PeopleProtocol: class {
   }

   extension PeopleProtocol where Self: People {
   }

But the method that will go in my protocol will be an init method which will be implemented by a class or its subClasess and will return only some specific type of objects.

some thing like this.

protocol PeopleProtocol: class {
   init() -> People
}

or i can do some thing like this

extension PeopleProtocol where Self : People {
   init()
}

But there are two problems,

  1. In the first approach if i put an init method in the protocol it don't allow me to put a return statement there like -> People in the first approach.

  2. In the second approach i have to provide a function body in the protocol extensions, so this thing will be out of question, as i don't know what specific type to return for this general implementation.

So any suggestions how i can call an init method and do either:

  1. Let the protocol (not protocol extension) to be implemented by only specific classe and its subClasses.
  2. Or return an instance of a certain from protocol extension method without giving its body.

Solution

  • You could add a required method that you only extend for the appropriate classes.

    for example:

    protocol PeopleProtocol
    {
      var conformsToPeopleProtocol:Bool { get }
    }
    
    extension PeopleProtocol where Self:People
    {
      var conformsToPeopleProtocol:Bool {return true}
    }
    
    class People  
    {}
    
    class Neighbours:People 
    {}
    
    extension Neighbours:PeopleProtocol // this works 
    {}
    
    class Doctors:People,PeopleProtocol // this also works
    {}
    
    class Dogs:PeopleProtocol // this will not compile
    {}
    

    This could easily be circumvented by a programmer who would want to, but at least it will let the compiler warn you if you try to apply the protocol to other classes.