2015-07-10 68 views

回答

1

Apple Documentation

注意:如果您的協議 標有@objc屬性

任擇議定書的要求只能被指定。

此屬性表示該協議應該暴露給 Objective-C代碼,並在使用Cocoa Swift和 Objective-C中進行了描述。即使您不與Objective-C進行互操作,如果您想要 指定可選要求,您需要使用@objc屬性標記您的協議 。

還要注意@objc協議只能通過類來採用,而不能通過結構或枚舉來採用 。如果您在 中將協議標記爲@objc以指定可選要求,則只能將 該協議應用於類類型。

+1

謝謝您的回答,我已經閱讀這片文檔後,提出了這個問題。我在那裏找不到真正的解釋。 – agy

+0

你看完整的文檔嗎? –

0

請檢查Apple Documentation:如果你的協議>標記有@objc屬性

此外,

任擇議定書的要求只能被指定。

該屬性表明該協議應該暴露給> Objective-C代碼,並在使用Cocoa Swift和> Objective-C中進行了描述。即使你不與Objective-C互操作,如果你想指定可選的需求,你也需要用@objc屬性標記你的協議。

還要注意@objc協議只能被類使用,而不能被結構或枚舉使用。如果您將協議標記爲@objc>以便指定可選要求,則只能將該協議應用於類類型。

同樣,這裏說明在斯威夫特文檔:

 
/// The protocol to which all types implicitly conform 
typealias Any = protocol 


/// The protocol to which all class types implicitly conform. 
/// 
/// When used as a concrete type, all known `@objc` `class` methods and 
/// properties are available, as implicitly-unwrapped-optional methods 
/// and properties respectively, on each instance of `AnyClass`. For 
/// example: 
/// 
/// .. parsed-literal: 
/// 
/// class C { 
///  @objc class var cValue: Int { return 42 } 
/// } 
/// 
/// // If x has an @objc cValue: Int, return its value. 
/// // Otherwise, return nil. 
/// func getCValue(x: AnyClass) -> Int? { 
///  return **x.cValue** 
/// } 
/// 
/// See also: `AnyObject` 
typealias AnyClass = AnyObject.Type 


/// The protocol to which all classes implicitly conform. 
/// 
/// When used as a concrete type, all known `@objc` methods and 
/// properties are available, as implicitly-unwrapped-optional methods 
/// and properties respectively, on each instance of `AnyObject`. For 
/// example: 
/// 
/// .. parsed-literal: 
/// 
/// class C { 
///  @objc func getCValue() -> Int { return 42 } 
/// } 
/// 
/// // If x has a method @objc getValue()->Int, call it and 
/// // return the result. Otherwise, return nil. 
/// func getCValue1(x: AnyObject) -> Int? { 
///  if let f:()->Int = **x.getCValue** { 
///  return f() 
///  } 
///  return nil 
/// } 
/// 
/// // A more idiomatic implementation using "optional chaining" 
/// func getCValue2(x: AnyObject) -> Int? { 
///  return **x.getCValue?()** 
/// } 
/// 
/// // An implementation that assumes the required method is present 
/// func getCValue3(x: AnyObject) -> **Int** { 
///  return **x.getCValue()** // x.getCValue is implicitly unwrapped. 
/// } 
/// 
/// See also: `AnyClass` 
@objc protocol AnyObject { 
}