2014-07-13 52 views
1

我想转换和现有的,工作目标c应用程序到swift和我有点绊倒与“闭包”。这里的老工作目标C座,使收益来自Web服务的值:如何在iOS Swift中将NSDictionary作为返回类型处理?

- (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的不是‘词典’亚型”

enter image description here 通过快速阅读本书后,这是我可以做的最好的教育尝试。我试了一些其他的东西,但每个都导致了另一种类型的错误。

我该如何使用swift工作?

编辑:我刚刚使用DictionaryDictionary<String, String>

我也应该注意到,我使用的是桥接报访问目标C代码(objectiveDDP)也试过。通过改变方法:这callMethodNamed是写在客观C作为可以在这里看到:https://github.com/boundsj/ObjectiveDDP/blob/master/ObjectiveDDP/MeteorClient.h#L47

更新

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

我们能够得到它的工作。但第二个我们尝试添加在闭包中,它开始抛出相同的原始错误。

+0

你有没有试过的NSDictionary替代字典? – Eugene

+0

@Eugene是的,我也试过Dictionary 。我很确定,在迅速的类型必须明确宣布,除非他们可以很容易地暗示。我可能错了,但 – Scott

回答

1

尝试从使用斯威夫特词典更改为显式使用的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)") 
     }) 
} 
+0

刚刚尝试过。这几乎是相同的错误:“'NSDictionary!'不是'NSDictionary'的子类型“ – Scott

+0

它看起来像它可能期望NSDictionary的隐式解包可选。你有没有尝试过! ? – connor

+0

我刚试过添加一个!到NSDictionary的结尾,似乎清除了错误。但后来我得到了NSError类似的错误,所以添加一个!直到结束,并导致另一个错误:无法转换表达式的类型字符串!键入String !.不知道这是从哪里来的。 – Scott

0

的技巧,在这种特殊情况下,是完全的忽略关闭的参数类型,并让编译器看着办吧。经过四周寻找,我发现this post这导致我的解决方案。

meteor.callMethodName("sayHi", parameters:["scotty"] , responseCallback: { 
     response, error in 
     let me:String = response["result"] as String! 
     println("called back \(me)") 
    }) 

如果不担心访问关闭参数,显然你也可以使用下划线完全忽略他们:

meteor.callMethodName("sayHi", parameters:["scotty"] , responseCallback: { 
     _ in 
     // Do something here 
    }) 
相关问题