0

I'm trying to write a Swift class (in Playground) that takes a dictionary of strings (such as PixelGreyScale) and applies each sequentially to each pixel in an image.

I have it working with a dictionary of class methods, but it's very slow and I can't pass parameters.

In the code below, my class is instantiated and then the Process method is run, taking in a dictionary of methods (a technique I saw on SO - is there a better way to dynamically run a method from a string variable?):

// Create an instance of the class, passing in the raw image
let p = ImageProcessor(src: rawImage);

// use a dictionary of method calls to queue up the process
let stack = [
    { p.PixelGreyScale() }
]

// run the process
p.Process(stack)

The Process method calls each method in the stack and sets the current pixel to the return value:

func Process(stack: [() -> Pixel]) {
        for y in 0..<rgba.height {
            for x in 0..<rgba.width {
                let index = y * rgba.width + x
                currentIndex = index
                rgba.pixels[index] = stack[0]()
            }
        }
}

This code runs, but I'm clearly not doing it right! I'm having the following problems:

  1. It takes an age to run, unless the stack dictionary is empty. Removing the stack[0]() call doesn't speed things up - it seems that having something in the stack causes a slowdown when getting the pixel at a given index.
  2. Because of how I'm using the stack dictionary to call methods, I can't pass parameters and have to resort to moving things into and out of class variables. I've tried using performSelector but got exceptions every time I tried to use parameters.

Is there a way of passing in a dictionary of strings and using this to control which methods are executed, with parameters and without speed issues?

Community
  • 1
  • 1
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • FYI: `[ ]` is an `Array`, not a `Dictionary`. A `Dictionary` is `[ : ]` –  Nov 20 '16 at 00:09
  • Ah yes, thank you. Learning Swift at the moment from a PHP/ASP.net background - but was at the end of my mental ability by the time I posted this! – Adam Hopkinson Nov 20 '16 at 14:39

0 Answers0