2014-06-05 28 views
24

我一直在尋找新的Swift語言,試圖找到什麼是在Swift中的接口(在java中)或協議(在objective-c)中的等價物,在因特網上衝浪並在由蘋果,我仍然無法找到它。在swift中,java接口或objective-c協議的等價物是什麼?

有沒有人知道這個組件在swift中的名稱是什麼,它的語法是什麼?

+4

在Swift中有協議。 [文檔鏈接](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_345) –

+5

「協議「 - 斯威夫特書第464頁 –

回答

35

Protocols in Swift非常相似Objc,除了你可以使用它們不僅對班,而且對結構和枚舉。

protocol SomeProtocol { 
    var fullName: String { get } // You can require iVars 
    class func someTypeMethod() // ...or class methods 
} 

順應協議是有點不同:

class myClass: NSObject, SomeProtocol // Specify protocol(s) after the class type 

您還可以擴展一個協議與默認(重寫)函數實現:

extension SomeProtocol { 
     // Provide a default implementation: 
     class func someTypeMethod() { 
      print("This implementation will be added to objects that adhere to SomeProtocol, at compile time") 
      print("...unless the object overrides this default implementation.") 
     } 
} 

注:默認的實現必須通過擴展來添加,而不是在協議定義本身中 - 協議不是一個具體的對象,所以它實際上並沒有附加方法體。將默認實現視爲C風格模板;本質上,編譯器複製聲明並將其粘貼到遵守協議的每個對象中。

+0

我得到了錯誤。請幫助'ViewController'不符合協議'SomeProtocol',其中ViewController是我的類,我已經實現了「SomeProtoco」 –

+2

你必須在你的MyClass中實現協議方法。這就是爲什麼你會遇到以上錯誤。在Java中以相同的方式。當你在你的課堂上實現一​​個接口。您還實施了抽象方法。 – user1154390

9

雨燕協議以及,here是相關文檔:

相關問題