Working with Objective-C blocks with Swift

2019-01-12 03:12发布

I'm having trouble using the Objective-C Firebase framework in a new Swift project. I'm coming from mostly a C# background so the Swift closure syntax isn't that clear yet.

Here's how the code work in Objective-C with f being the Firebase object

[f observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
  NSLog(@"%@ -> %@", snapshot.name, snapshot.value);
}];

XCode auto suggests this syntax, and I have yet to find a working solution.

f.observeEventType(FEventTypeValue, withBlock: ((FDataSnapshot!) -> Void)?)

I'd like assign the FDataSnapshot data to a variable as the Objective-C example is doing. Thanks

3条回答
走好不送
2楼-- · 2019-01-12 03:47

Swift blocks are interchangeable with Objective-C blocks, so it ought to be something like:

f.observeEventType(FEventTypeValue, withBlock: { 
    snapshot in 
    println("\(snapshot.name) -> \(snapshot.value)")
})
查看更多
萌系小妹纸
3楼-- · 2019-01-12 04:03

To throw in implied names and tail closures, you can use:

f.observeEventType(FEventTypeValue) {
    println("\($0.name) -> \($0.value)")
}
查看更多
Bombasti
4楼-- · 2019-01-12 04:04

Here's the Swift equivalent:

f.observeEventType(FEventTypeValue, withBlock: {
    snapshot in
    println("\(snapshot.name) -> \(snapshot.value)")
})

The key here is the in keyword to assign arguments to the closure to variables

查看更多
登录 后发表回答