0

If I have functions in a Swift class like:

class MyClass: NSObject {
    class func drawingOne(frame: CGRect) {}
    class func drawingTwo(frame: CGRect) {}
}

Note, I can not edit the code in the above class. It is provided by a third party.

How can I pick a function matching a string? For example:

let function = function(forName: "drawingOne")

to give the function:

drawingOne

So, I could do something like:

guard let drawFunction = function(forName: "drawingOne")
    else { return }
if let drawFunction = drawFunction as? ((CGRect) -> Void) {
    drawFunction(frame: bounds)
}
barefeettom
  • 121
  • 1
  • 5
  • You will need to create a method that takes a string, switch its value and return the appropriate method based on it. – Leo Dabus Dec 28 '17 at 07:06
  • I can not edit the class containing the functions. It is provided by a third party. And of course I can create a giant `if`/`then` or `switch`/`case`, mapping each explicit string to a function, but I'm looking for something dynamic. – barefeettom Dec 28 '17 at 07:11
  • 1
    You should use `responseToSelector` and `performSelector`. Please check this thread https://stackoverflow.com/questions/24167791/what-is-the-swift-equivalent-of-respondstoselector – t4nhpt Dec 28 '17 at 07:15
  • I can get: `String -> Selector`. But I want `String -> function`. I would settle for: `Selector -> function` since I can obviously chain them. – barefeettom Dec 28 '17 at 07:24
  • I think it is highly possible that this is impossible in Swift. Swift is a _really_ static language... – Sweeper Dec 28 '17 at 07:28

0 Answers0