Joe C
Joe C

Reputation: 2834

How to declare / implement a Swift function with a nullable pointer argument in Objective-c?

My Swift code has this:

@objc protocol MyDelegate {
    func buttonPressed(buttonNum: Int, packet: Packet?)
}

Then my objective-c code for the delegate has this:

- (void)buttonPressed:(NSInteger)buttonNum :(Packet * _Nullable) packet {
}

But I'm getting a "function not implemented" warning. My experiments seem to indicate that there's something wrong with that nullable pointer. I.e. if there was no "?" in the Swift proto declaration and no "_Nullable" in the Object-c function then all is well.

Does anyone know what I need to do on the Objective-c side to implement that function for that proto?

Upvotes: 0

Views: 213

Answers (1)

Cristik
Cristik

Reputation: 32904

The problem is not due to the nullability of the parameter, but due to the selector name.

func buttonPressed(buttonNum: Int, packet: Packet?)

should get a

buttonPressed:packet:

Objective-C function. Yours is buttonPressed:: - no label for the second parameter.

The confusion might have been caused by the fact that Swift automatically infers labels starting with the second parameter - if no label is specified, then the label is assumed to be the parameter name. This is why in Swift you'd need to call the protocol function as buttonPressed(arg1, packet: arg2).

Now you can either add the packet label to the Objective-C selector, or you can remove it from the Swift function declaration, like this:

func buttonPressed(buttonNum: Int, _ packet: Packet?)

You can then call it from Swift like buttonPressed(arg1, arg2). It's up to you which approach you choose, although I'd recommend going with the labeled one as is more clear, at least in Objective-C.

Upvotes: 2

Related Questions