Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

closures - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...