0

I have a swift protocol having following delegate method

@objc public protocol CuteDelegate: NSObjectProtocol {
    @objc func myCuteFunc(name: NSString)
}

I have declared delegate object in swift as well

weak var delegate : CuteDelegate?

In my objective C controller where I am implementing the above delegate method is as follows

-(void)myCuteFunc:(NSString* )name{

}

But while calling the method in swift controller

 self.delegate?.myCuteFunc(name: str as NSString)

I get unrecognized selector sent to instance

Any clue what's the issue

1
  • Can you share your declaration of delegate Commented Aug 16, 2018 at 12:02

1 Answer 1

3

You need to account for the first arguments's name:

Either:

  1. Make your Objective-C function -(void)myCuteFuncWithName:(NSString* )name

Or:

  1. Change your protocol to @objc func myCuteFunc(_ name: NSString) and call it with self.delegate?.myCuteFunc(str)

This is just an artifact of the way Objective-C function names work vs. the way Swift names its arguments. Objective-C has no way of naming the first argument (which is usually described by the function name), so if Swift has a label for the first argument, the convention used is to add With plus the argument name (with the argument name capitalized) to the function name. By adding _, you make the first argument unnamed and that translates better to the Objective-C naming convention.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for saving my day but still wondering why _ name: needed , if you could explain?
It's just an artifact of the way Objective-C works vs. the way Swift names its arguments. Objective-C has no way of naming the first argument, so if Swift has one, the convention used is to add With plus the argument name with the argument name capitalized. By adding _, you make the first argument unnamed, so that translates better to the Objective-C naming convention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.