Reputation: 543
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
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
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