gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:42:46 25 4
gpt4 key购买 nike

如何将此代码从 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

最佳答案

您的 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)

请注意,不仅是参数命名,而且我使用驼峰命名约定并且没有下划线。

坦率地说,我也会更具体地向字典输入键和值类型,但我会把它留给你。 Swift 的主要优点之一是它比 Objective-C 更重视类型安全,因此除非万不得已,否则我们通常不会使用 NSObjectAnyObject

关于objective-c - 如何将此代码从 objective-c 更改为 swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com