11

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

1
  • 2
    Closures in Swift are like anonymous methods in C#. For example, Action<T> translates to (T) -> Void and Func<TArg, TResult> becomes (TArg) -> TResult. Commented Jun 11, 2014 at 17:49

3 Answers 3

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

I was wondering if you can take a look at this: gist.github.com/acegreen/05282d20eb45de8d30d5
4

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

f.observeEventType(FEventTypeValue) {
    println("\($0.name) -> \($0.value)")
}

7 Comments

Doesn't it need the last parameter name, though?
No, it uses implied naming and typing as long as there's a single trailing block and you put the '{' on the same line as the ')'
How does it know the name of the withBlock: parameter, though? I thought named parameters still needed to be named. Is this documented anywhere?
It's somewhere in the iTunes book. Look through the section on closures, I think they call it tail closures.
@AlexWayne It works for any function that ends with a closure argument, the names and types are irrelevant.
|
1

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)")
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.