gpt4 book ai didi

objective-c - 如何在 iOS swift 中处理 NSDictionary 作为返回类型?

转载 作者:行者123 更新时间:2023-11-28 07:17:45 24 4
gpt4 key购买 nike

我正在尝试将现有的工作 objective c 应用程序转换为 swift,但我有点被“闭包”绊倒了。这是旧的工作 objective-c block ,它从 Web 服务返回一个值:

- (IBAction)didTapSayHiButton {
[self.meteor callMethodName:@"sayHelloTo" parameters:@[self.username.text] responseCallback:^(NSDictionary *response, NSError *error) {
NSString *message = response[@"result"];
[[[UIAlertView alloc] initWithTitle:@"Meteor Todos" message:message delegate:nil cancelButtonTitle:@"Great" otherButtonTitles:nil] show];
}];
}

所以在这里我要么取回字典要么回复。它有效。下面是我尝试用 swift 解决这个问题的方法(方法略有不同):

@IBAction func sayHi(sender : AnyObject) {
var params = [
"name": "Scotty"
]
meteor.callMethodName("sayHi", parameters: params, responseCallback: {
(response: Dictionary<String, String>, error: NSError) in
println("the name recieved back is: \(response)")
})
}

我在 xCode 中遇到的错误:“NSDictionary 不是‘Dictionary’的子类型”

enter image description here看完这本 swift 书后,这是我能做出的最好的教育尝试。我尝试了一些其他的东西,但每一个都导致了另一种类型的错误。

我如何使用 swift 使其工作?

编辑:我也试过只使用 DictionaryDictionary<String, String>

我还应该注意,我正在使用桥接 header 来访问 Objective-C 代码 (objectiveDDP)。那callMethodNamed是用 objective-c 编写的,如下所示:https://github.com/boundsj/ObjectiveDDP/blob/master/ObjectiveDDP/MeteorClient.h#L47

更新:通过将方法更改为:

meteor.callMethodName("sayHi", parameters:["scotty"] , responseCallback:nil)

我们能够让它发挥作用。但是当我们尝试添加闭包时,它开始抛出相同的原始错误。

最佳答案

尝试从使用 Swift 字典更改为显式使用 NSDictionary:

 @IBAction func sayHi(sender : AnyObject) {
var params: NSDictionary = [
"name": "Scotty"
]
meteor.callMethodName("sayHi", parameters: params, responseCallback: {
(response: NSDictionary!, error: NSError) in
println("the name recieved back is: \(response)")
})
}

关于objective-c - 如何在 iOS swift 中处理 NSDictionary 作为返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24724713/

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