3

As mentioned in the title, some standard Swift protocols get away with declaring optional requirements without the use of @objc. For example:

public protocol UIScrollViewDelegate : NSObjectProtocol {

    @available(iOS 2.0, *)
    optional public func scrollViewDidScroll(_ scrollView: UIScrollView) // any offset changes
    @available(iOS 3.2, *)
    optional public func scrollViewDidZoom(_ scrollView: UIScrollView) // any zoom scale changes
    ...
} 


public protocol UIApplicationDelegate : NSObjectProtocol {
    ...
    @available(iOS 2.0, *)
    optional public func applicationDidBecomeActive(_ application: UIApplication)

    @available(iOS 2.0, *)
    optional public func applicationWillResignActive(_ application: UIApplication)
    ...
}

The following test failed with the expected compile error due to the missing @objc:

public protocol Test: NSObjectProtocol {
    optional func test()
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Dario JG
  • 67
  • 7
  • 1
    Those protocols are written in Objective-C, it just doesn't mark the generated swift headers as `@objc`. – dan Mar 07 '18 at 22:03

3 Answers3

2

Optional protocol method options are available only for Objective-C based protocol. UIScrollViewDelegate and UIApplicationDelegate are Objective-C based protocol. That means you don't need to say its @objc. The code which you seeing are bridged file between Objective-C and Swift. So that Swift can have access to those methods. Your protocol Test is defined in Swift. Even though you adapting NSObjectProtocol the class not exposed to Objective-C runtime, where the optional option is available. For this reason, you need to explicitly mention this protocol is exposed to Objective-C with @objc.

vinothp
  • 9,939
  • 19
  • 61
  • 103
0

I guess that is because the UIScrollViewDelegate and UIApplicationDelegate are Objective-C classes bridged on Swift for you.

The @objc bridges Swift to Objective-C https://stackoverflow.com/a/30795237/440299

mt81
  • 3,288
  • 1
  • 26
  • 35
0

You can define optional protocol methods by using extensions

important :

Both protocol and extension should be public to be accessible outside of the framework

public protocol MyProtocol {
    func method()
}

public extension MyProtocol {
    func method() {} 
}
Community
  • 1
  • 1
Husam
  • 8,149
  • 3
  • 38
  • 45