Search code examples
iosswiftipadinterfaceprotocols

Swift instance of protocol


Can i create an instance of an protocol in swift?

Like in java an instance of an interface?

Java:

public interface test {
    void test();
}

new test() {
    @Override
    public void test() {
        //...
    }
}

Swift:

protocol ITransmitter {
    func onExecuteSuccess(data:String)
}

//instance???

Solution

  • You can not create an instance of protocol.

    For example

    protocol ITransmitter {
        func onExecuteSuccess(data:String)
    }
    
    var protocolInstance : ITransmitter = ITransmitter() // << Not allowed. This is an error
    

    But however you can refer an object in your code using Protocol as the sole type. Let us say you have a class that conforms to this protocol, but in your code your requirement is only to be able to call the protocol method on it and you don't care any other methods the instance of the class supports.

    For example-

    class A{
      func foo(){
    
      }
    }
    extension A : ITransmitter{
    
     func onExecuteSuccess(data:String){
        //Do stuff here
      }
    }
    
    //This function wants to run the ITransmitter objects, so it uses only protocol //type for its argument. The transmitter can be of any class/struct, but has to //conform to ITransmitter protocol
    
    func runTransmittor(transmitter : ITransmitter){
         //some other statements here..
         transmitter. onExecuteSuccess(data :SomeData){
         }
    }