How to define additional protocol requirements in swift?

As far as I know, you need to annotate the function this way:

@objc MyProtocol{
optional func yourOptionalMethod()
}

But why use the @objc annotation?

+1
source share
2 answers

From Apple Documentation :

Note

Additional protocol requirements can only be specified if your protocol is marked with the @objc attribute.

This attribute indicates that the protocol must be Objective-C and is described in Using Swift with Cocoa and Objective-C. Even if you do not interact with Objective-C, you must mark your protocols with the @objc attribute if you want to specify additional requirements.

, @objc , . @objc , .

+1

, Apple:

,

, @objc.

, < Objective-C Swift Cocoa > Objective-C. Objective-C, @objc, .

, @objc , > . @objc > , .

, Swift Documentation:

/// 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 {
}
0

Source: https://habr.com/ru/post/1678345/


All Articles