如何将此代码从objective-c更改为swift?

时间:2016-05-28 02:19:48

标签: objective-c swift

如何将此代码从objective-c更改为swift:

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

}

我写信给:

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

    }

但不行......

//错误地放

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

1 个答案:

答案 0 :(得分:1)

您的Objective-C方法声明使用的方法签名样式没有命名参数,我们通常不再使用它们。您是否喜欢这种风格,还是会使用更现代的风格?但是如果你真的想要实现没有命名参数的Swift方法,那就像是:

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

然后你可以从Swift中调用它:

obj.get_answer_dict(dictionary1, dictionary2)

或者来自Objective-C:

[obj get_answer_dict:dictionary1 :dictionary2];

话虽如此,我衷心鼓励您使用更传统的方法命名约定,例如。

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

你称之为

[obj retrieveAnswerWithDictionary1:someDictionary dictionary2:someOtherDictionary];

Swift的等价物是:

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

这将被称为:

obj.retrieveAnswerWithDictionary1(someDictionary, dictionary2: someOtherDictionary)

注意,不仅命名参数,而且我使用camelCase命名约定而没有下划线。

坦率地说,我也会在字典中键入键值和值类型时更具体,但我会把它留给你。 Swift的一个主要优点是比Objective-C更重视类型安全,因此我们通常不会使用NSObjectAnyObject,除非我们绝对不得不这样做。