Swift协议实例

时间:2016-04-07 06:52:01

标签: ios swift ipad interface protocols

我可以在swift中创建一个协议实例吗?

在java中是一个接口的实例吗?

Java:

public interface test {
    void test();
}

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

夫特:

protocol ITransmitter {
    func onExecuteSuccess(data:String)
}

//instance???

2 个答案:

答案 0 :(得分:4)

您无法创建协议实例。

例如

protocol ITransmitter {
    func onExecuteSuccess(data:String)
}

var protocolInstance : ITransmitter = ITransmitter() // << Not allowed. This is an error

但是你可以使用Protocol作为唯一类型引用代码中的对象。假设您有一个符合此协议的类,但在您的代码中,您的要求只是能够在其上调用协议方法,并且您不关心该类实例支持的任何其他方法。

例如 -

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){
     }
}

答案 1 :(得分:0)

我创建了符合协议和该类的指定对象的内部类

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?