The Pedestrian
The Pedestrian

Reputation: 543

why do I have to mark both the protocol & contained optional functions in a swift protocol as @objc?

I have discovered some inconsistency when declaring optional functions in a protocol. While declaring a function in a protocol optional, I have to mark both the protocol and the optional function as @objc. I then looked up the documentation for UICollectionViewDataSource and found that there was no such requirement over there for declaring optional functions.

I have tried to confirm to NSObjectProtocol but the compiler still requires me to mark the protocol as well as the optional function as @objc. Can someone please enlighten me regarding the same?

Upvotes: 0

Views: 228

Answers (2)

Rob Napier
Rob Napier

Reputation: 299555

UICollectionViewDataSource is imported from ObjC. The auto-generated Swift header doesn't insert @objc on every element. It is common for these headers to be invalid Swift (for example, they define structs and classes without implementations, which isn't valid Swift).

When you're writing Swift (rather than looking at auto-generated headers), you need to tell the compiler that it needs to bridge certain things to ObjC, and you do that with @objc. Imported ObjC doesn't have to be bridged.

Upvotes: 1

Zaman
Zaman

Reputation: 1

If you want to make optional function in a protocol then you have to declare in this manner @objc protocol MyOptionalProtocol { @objc optional func optionalFunction()
}

Upvotes: 0

Related Questions