2016-04-07 241 views
0

我可以在swift中創建一個協議實例嗎?Swift協議實例

像在java中的一個接口的實例?

的Java:

public interface test { 
    void test(); 
} 

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

斯威夫特:

protocol ITransmitter { 
    func onExecuteSuccess(data:String) 
} 

//instance??? 
+0

好,我們可以做這樣的事情 VAR callHandler: CallsHanlerProtocol = CallHandler() –

回答

4

不能創建協議的一個實例。

例如

protocol ITransmitter { 
    func onExecuteSuccess(data:String) 
} 

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

但是無論你如何可以參考使用協議作爲唯一的類型代碼的對象。讓我們說你有一個符合這個協議的類,但是在你的代碼中,你的要求是隻能調用它的協議方法,而不關心類支持的任何其他方法。

對於示例 -

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