2014-12-07 29 views
0

我想弄清楚如何在Swift中複製一個示例Java公共接口。這是我想到的。你會如何在Swift中複製這個Java公共接口?

下面是一個例子的Java公共接口:

public interface TestInterface { 
    public static int MSG_1   = 0x11; 
    public static int MSG_2   = 0x22; 
    public static int MSG_3   = 0x33; 

    public int getMessageType(); 
} 

然後在一個新的類將實施的TestInterface,例如:

import com.myTestApp.TestInterface; 

public class msg1Type implements TestInterface { 
     public int getMessageType() { 
      return MSG_1; 
     } 
} 

在斯威夫特我已經做了如下 - 添加一個名爲TestInterface.swif的文件:

import Foundation 

    class TestInterface { 
     let MSG_1     :Int = 0x11 
     let MSG_2     :Int = 0x22 
     let MSG_3     :Int = 0x33 

     let getMessageType((void)->Int) 
    } 

然後在實現Tes的類tInterface的getMessageType()函數,如:

import Foundation 

class msg1Type : TestInterface { 

     func getMessageType() -> Int { 
      return MSG_1; 
     } 
} 

什麼是最好的方法來實現這個實驗?

+0

你的代碼出現,以反映基本斯威夫特語言概念,包括協議,初始化,甚至函數簽名缺乏瞭解。有人可能會提供正確的答案,但我強烈建議您閱讀Apple的官方Swift書籍,並節省大量不必要的試驗和錯誤。 – mattt 2014-12-07 00:33:55

+0

@Matt - 謝謝,實際上我會花一些時間閱讀,而不是試圖學習SWIFT的蠻力。我喜歡使用其他語言的示例,然後移植,以便了解兩者之間的差異。也許不是最好的方法。 – Mavro 2014-12-07 00:56:55

回答

1

我想我可以看到你想要做什麼。 (這與C++相似),但是在使用其它協議如'Protocols'(而不是Java的'Interface')之間存在一些混淆。

,而不是...

我建議稍微簡單的解決方案:
創建帶有默認方法的一類,你再後來覆蓋在一個子類

首先創建超一流您的郵件常量和默認方法

class TestInterface 
{ 
    let MSG_1:Byte = 0x11; 
    let MSG_2:Byte = 0x22; 
    let MSG_3:Byte = 0x33; 

    func getMessageType() -> Byte 
    { 
     return 0 
    } 
} 

然後你就可以延長超類並重寫消息類型方法

class SecondInterface : TestInterface 
{ 
    override func getMessageType() -> Byte 
    { 
     return MSG_2 
    } 
} 

(我個人認爲這是很好的做法,做跨語言實驗)

+0

謝謝!是的,這是完美的。 – Mavro 2014-12-09 17:27:10

0

我完全贊同亞光。

class TestInterface { 

    let MSG_1 :Int = 0x11 
    let MSG_2 :Int = 0x22 
    let MSG_3 :Int = 0x33 

    func getMessageType() ->Int { 
     return MSG_1 
    } 
} 
2

你在找什麼是protocols

enum MessageType: Int { 
    case MSG_1 = 0x11, 
    case MSG_2 = 0x22, 
    case MSG_3 = 0x33 
} 

protocol TestProtocol { 
    func getMessageType() -> MessageType 
} 

這可以這樣實現:

class Msg1Type: TestProtocol { 
    func getMessageType() -> MessageType { 
     return MSG_1 
    } 
} 

不要盲目從Java轉換概念成其他語言,試圖從頭開始,如果可能的學習斯威夫特,

+0

謝謝。會做! – Mavro 2014-12-07 00:58:55