libai
libai

Reputation: 195

how to change this code from objective-c to swift?

how to change this code from objective-c to swift :

- (void)get_answer_dict:(NSDictionary *)dict_1:(NSDictionary *)dict_2{

}

i write to:

func get_answer_dict(dict_1: [NSObject: AnyObject], dict_2: [NSObject: AnyObject])
    {

    }

but not ok .....

//err out put

2016-05-28 10:09:23.815 Meet Design[32299:919087] -[Meet_Design.DesignerScroll get_answer_dict::]: unrecognized selector sent to instance 0x7ffa8af32670
2016-05-28 10:09:23.825 Meet Design[32299:919087] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Meet_Design.DesignerScroll get_answer_dict::]: unrecognized selector sent to instance 0x7ffa8af32670'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010c67fd85 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010bd44deb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010c688d3d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010c5cecfa ___forwarding___ + 970

Upvotes: 1

Views: 107

Answers (1)

Rob
Rob

Reputation: 438467

Your Objective-C method declaration is using a method signature style without named parameters, which we generally don't use anymore. Are you wed to that style, or would you use the more contemporary style? But if you really wanted to implement a Swift method without named parameters, it would be something like:

func get_answer_dict(dict_1: [NSObject: AnyObject]!, _ dict_2: [NSObject: AnyObject]) {
   ...
}

You could then call that from Swift as:

obj.get_answer_dict(dictionary1, dictionary2)

Or from Objective-C:

[obj get_answer_dict:dictionary1 :dictionary2];

Having said that, I'd heartily encourage you to use more conventional method naming conventions, eg.

- (void)retrieveAnswerWithDictionary1:(NSDictionary *)dictionary1 dictionary2:(NSDictionary *)dictionary2 {
    ....
}

And you'd call that as

[obj retrieveAnswerWithDictionary1:someDictionary dictionary2:someOtherDictionary];

The Swift equivalent would be:

func retrieveAnswerWithDictionary1(dictionary1: [NSObject: AnyObject], dictionary2: [NSObject: AnyObject]) {
    ...
}

Which would be called:

obj.retrieveAnswerWithDictionary1(someDictionary, dictionary2: someOtherDictionary)

Note, not only are the parameters named, but I use camelCase naming convention and no underscores.

Frankly, I would be more specific in the typing of the key and value types to the dictionaries, too, but I'll leave that to you. One of the key benefits of Swift is that takes type-safety more seriously than Objective-C, so we generally wouldn't use NSObject or AnyObject unless we absolutely had to.

Upvotes: 1

Related Questions