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?
Are you going to return
randFloat? WillrandFloatuse any states not separable from the nearby functions (i.e. israndFloata 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: