views:

54

answers:

2

In my constructor, I want to create a random color.

Therefore, I need three random 7-bit floats in the range of 0…1 that make up the red, green and blue component of the color. Instead of writing the rather long random() % 128 / 128.0 three times, I put that in a block:

CGFloat (^randFloat)() = ^(){ return random() % 128 / 128.0; };
color = CGColorCreateGenericRGB(randFloat(), randFloat(), randFloat(), .5);

Is that a valid way to use blocks?
If not, what would you use instead?

+5  A: 

Are you going to return randFloat? Will randFloat use any states not separable from the nearby functions (i.e. is randFloat a closure)? If not, it's more portable (the iPhone official SDK doesn't support blocks yet, for example) and efficient to create a static function outside of the function:

static CGFloat randFloat() {
    return random() % 128 / 128.0;
}
...
color = CGColorCreateGenericRGB(randFloat(), randFloat(), randFloat(), .5);
KennyTM
iPhone OS doesn't support blocks out of the box yet, but you can still use them with PLBlocks.
Chuck
@Chuck: Ah right. Rephrased a bit.
KennyTM
No, randFloat will not use any external variables. It is just meant as a shorthand for `random() % 128 / 128`. Thanks!
BastiBechtold
+1  A: 

There's nothing wrong with using a block that way. I personally wouldn't in this case, since creating a block for the operation actually makes the code longer. But it seems fine in principle. If this function is never used anywhere else, why give it a larger scope than it needs?

Chuck