Search code examples
iosswiftprotocols

How to define optional methods in a Swift protocol with Swift parameters?


TL;DR

How can I define optional methods in a swift protocol that accept custom typed parameters?

The case

I understand that the way to define optional methods in a swift protocol is using the @objc flag. Like so:

@objc protocol someSweetProtocol {
    optional func doSomethingCool()
}

But when I wanted to use my custom type for the parameter, like so:

@objc protocol someSweetProtocol {
    optional func doSomethingCool(🚶🏼: HSCoolPerson)
}

I got this error:

enter image description here

Which is not cool.

How can this problem be solved? Also can you explain why this is happening?

Addendum

This is how HSCoolPerson is defined:

class HSCoolPerson {
    ...
    ...
    ...
}

Nothing special there...


Solution

  • The problem is this:

    class HSCoolPerson {
        // ...
    }
    

    As the error message plainly tells you, that type, the class HSCoolPerson, is completely invisible to Objective-C. And a protocol optional method is an Objective-C language feature; Swift merely borrows it, as it were. (That's why you have to say @objc protocol to get this feature.) So any time you want to define a protocol optional method, you have to do it in a way that Objective-C can understand, because it is Objective-C that is going to do the work for you.

    To expose this class to Objective-C, simply derive it from NSObject:

    class HSCoolPerson : NSObject {
        // ...
    }
    

    Problem solved.