I have a custom graphics class (think canvas)… This has one major task and that is to display an image on the screen. This class has a key property with (currently 57 values).
So based on the value of that key, the canvas will be one of 57 images.
Right now the code looks like this (and it does “work”)
private func drawIMAGE(imgKey:Int) {
switch imgKey {
case 1 : draw_image_1
case 2 : draw_image_2
...
case 57 : draw_image_57
}
}
Why wouldn’t you have a property holding the image to draw and a generalized function that draws that image? Are the functions that draw significantly different?
yes the functions are all quite differnet… and a given image might change (become wider, taller, change colors etc)… but it caches the image … so it only recreates it if it changes
each image is somewhat dynamic, think Xojo IDE controls in the designer
The only way I can think of to make this less gnarly and more easily maintained, at some performance expense, would be using reflection (.NET) or introspection (Xojo, Swift). Then you would make the function call after determining the function name from the imgKey (or call a DrawImage() method in a static class whose name is thusly determined, etc).
For instance instead of storing an imageKey with an object, you can store a NSSelector, then use the sendmessage API to execute that function. I’ve used this technique in several places, but not with this many methods.
I like your solution. Technically you are still making a decision at draw time but it should be considerably faster than a case statement for routing (even if you optimize by putting the most common / likely cases first) and there’s no overhead for late-bound tricks. Even “wasting” an element zero is a good thing because you’re saving a subtraction on each call to draw an image.
Seems to implement such a thing in Swift requires ObjC code bound to Swift, and it is not a recommended practice, since Swift considers the use of pointers to be “unsafe”