如何在swift中定义可选的协议要求?

时间:2015-07-10 06:25:21

标签: objective-c swift

据我所知,您需要以这种方式注释函数:

@objc MyProtocol{
optional func yourOptionalMethod()
}

但为什么需要@objc注释?

2 个答案:

答案 0 :(得分:1)

来自Apple Documentation

  

请注意

     

只有在您的协议中才能指定可选的协议要求   标有@objc属性。

     

此属性表示应该公开协议   Objective-C代码和使用Swift with Cocoa和   Objective-C的。即使您没有与Objective-C进行互操作,也可以   如果需要,需要使用@objc属性标记协议   指定可选要求。

     

另请注意,@ objc协议只能由类采用,而不能   通过结构或枚举。如果您将协议标记为@objc in   为了指定可选要求,您将只能申请   类协议的类协议。

答案 1 :(得分:0)

请检查Apple Documentation

此外,

  

只有在您的协议使用@objc属性进行标记时,才能指定可选的协议要求。

     

此属性指示协议应该暴露于> Objective-C代码,并在使用Swift with Cocoa和> Objective-C中进行描述。即使您没有与Objective-C进行互操作,如果您想要>指定可选要求,也需要使用@objc属性标记您的协议。

     

另请注意,@ objc协议只能由类采用,而不能由结构或枚举采用。如果您在>顺序中将协议标记为@objc以指定可选要求,则您只能将>该协议应用于类类型。

再次,在Swift文档中解释:

/// 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 {
}
相关问题