1

I'm trying to pass a dictionary object to an Objective C protocol using swift.

the protocol code snippet is as follows:

@protocol MessageDelegate

- (void)handleNewMessageArrived:(NSDictionary *)messageContent;

@end

and this is the swift class the implements the protocol:

class ViewController: UIViewController, MessageDelegate
{
 ...

 func handleNewMessageArrived(messageContent : NSDictionary!)
 {
  ...    
 }
}

But the build fails, and the error I get is:

"the type 'ViewController' does not conform to protocol 'MessageDelegate"

I looked at this SO Question but it deals with a specific object type.

is there an error in the way I declare\implement the delegate method? or in the way I assume the arguments are mapped in swift?

I'm new to Swift so any Help will be much appreciated.

2 Answers 2

7

Try implementing the method in your Swift class like this:

func handleNewMessageArrived(messageContent: [NSObject : AnyObject]!) {
    // Handle the message
}
Sign up to request clarification or add additional context in comments.

4 Comments

@sbooth I haven't spent much time with Swift. Can you explain why you have to make the messageContent parameter an anonymous pointer in Swift? It's not id type (the equivalent) in Objective-C.
@DuncanC The messageContent parameter is an implicitly unwrapped optional containing a Swift dictionary with NSObject keys and AnyObject values. This corresponds closely to NSDictionary and is the result of Swift's automatic bridging.
So by default container objects like dictionaries are containers of a specific type (e.g. dictionary of strings?) Isn't an NSDictionary a concrete type, and a valid parameter in Swift though?
All Swift containers are type-safe (a good thing). NSDictionary is also a valid type in Swift, but the Swift <-> Objective-C bridge converts the types automatically.
1

In case of Swift 3, this is what you will need

func handleNewMessageArrived(messageContent: [AnyHashable : Any]!) {
    // Handle the message
}

Comments

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.