Question

Can we write Continuation passing style code in Objective C? If yes, could you please give some examples?

Was it helpful?

Solution

Continuation Passing Style, or CPS, is a style of programming using anonymous functions to replace return statements. Instead of returning a value, a function will take another function as a parameter. Then, when it gets to the point where it would have returned a value, it calls the passed-in function with the value as a parameter instead.

In Objective-C, we now have anonymous functions in the form of blocks, so CPS can be achieved using blocks.

Here's an example of how CPS looks. This is the standard-style code:

NSString *string = [obj stringWhatever];
    // use string

And here it is converted to Continuation Passing Style:

[obj stringWhatever: ^(NSString *string) {
    // use string
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top