2015-07-10 50 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 { 
}