Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Objective-C blocks with Swift

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

like image 881
Beanwah Avatar asked Jun 11 '14 17:06

Beanwah


2 Answers

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

like image 151
Jack Avatar answered Sep 18 '22 08:09

Jack


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

f.observeEventType(FEventTypeValue) {
    println("\($0.name) -> \($0.value)")
}
like image 34
David Berry Avatar answered Sep 20 '22 08:09

David Berry