Add `@objc` keyword to methods implementing @objc protocols

Description

Refer to this sample:
http://swiftify.me/bca7bo/2

If an optional protocol function (`optionalFunc`) is declared with `@objc` keyword, the corresponding Swift class method (implementing this protocol) should be also declared with `@objc` keyword.

Environment

None

Activity

Show:
Alex Petuschak
May 20, 2020, 9:47 AM

The problem I see with your implementation is that any method with such a signature will be declared as @objc, even if `MYKlass` doesn't implement `MYProtocol`:

http://swiftify.me/bca7bo/3

We could potentially use ClassAccessor.InheritsFrom()method to check the inheritance, and add selector names to MethodsRequiringObjCKeyword.

However, the added@objckeyword does no harm in most cases, and I like the simplicity of your implementation.

 

However, the more interesting thing is that I no longer understand the initial objective of creating this task - it was pretty long ago, and I can’t find the initial source.

The best I can see is that the @objcbehavior for protocol method and method implementing this protocol should be the same.

 

Could you please review this task, and suggest:

  1. Whether we include this change or not?

2. Long term, would you prefer @objc optionalor “optional protocol extension” way when converting an Objective-C optional protocol method to Swift? See https://medium.com/@ant_one/how-to-have-optional-methods-in-protocol-in-pure-swift-without-using-objc-53151cddf4ce.

I think, @objc optionalis still a better fit since we are dealing with code gradually migrated from Objective-C to Swift.

Ivan Kh
May 26, 2020, 3:40 PM

Whether we include this change or not?

I don’t see reasons for this change. Sample code compiles and works right without @objc keyword for class.

 

@objc optional:

+ User have to pay attention to optional method (it will be compilation error in calls)

- Usage of objc keywords

“optional protocol extension”

+ Modern swift way

- You have to care about non optional return value

- The code will become different from original

 

would you prefer @objc optionalor “optional protocol extension”

From +- above I choose @objc optional

Alex Petuschak
May 26, 2020, 5:12 PM

Thanks, - agreed.

I think this was an issue with a specific project, but I agree with your judgment and it seems not worth figuring out why.

Just for the history, here is the screenshot of the changes: https://take.ms/XN05j

Otherwise, abandoning this and deleting the branch / PR.

Assignee

Ivan Kh

Reporter

Alex Petuschak

Labels

None

Git Branch Name

Feature/ObjCKeywordMethodImplementation

GitHub Issue

None

Components

Fix versions

Priority

Medium
Configure