2

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???
2
  • well we can do something like that var callHandler: CallsHanlerProtocol = CallHandler() Commented Apr 7, 2016 at 7:02
  • Hay, you also can not create an instance of a java interface. Commented Aug 7, 2021 at 19:19

2 Answers 2

7

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){
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I created inner class which conforms to protocol and assigned object of that class

class Outer {
    private final class Inner: ITransmitter {
        unowned let parent: Outer
        init(parent: Outer) {
            self.parent = parent
        }
        func onExecuteSuccess(data:String){
        }
    }
    var inner: Inner! = nil
    init() {
        inner = Inner(parent: self)
    }
}

Do Swift inner classes have access to self of outer class?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.