0

How do you call a function based on a function name String var and pass in an argument to the function? I was trying to do this is Swift and finally got it.

mutable2112
  • 439
  • 4
  • 15

1 Answers1

0

In Swift 3 - inbound 'params' as [String: Any], where params["function"] == "getSomeData"

let funcName = String(format: "%@:", (params["function"] as? String)!)
let selector = NSSelectorFromString(funcName)
self.perform(selector, with: params)

func getSomeData(_ params: [String: Any]) {
  print(params)
}
mutable2112
  • 439
  • 4
  • 15
  • Your solution works, but is not recommended. Swift is moving away from creating selectors from strings. I would not be at all surprised if Swift removes this ability completely in the near future. Rather, you should use the Swift version of the function signature, and NOT build a selector from a string at all. – Duncan C Feb 14 '17 at 13:59
  • 2
    what is the recommended way? – Vinu David Jose Apr 10 '17 at 07:19
  • 1
    Yes Duncan C, thanks for your feedback; but sorry but it isn't very constructive? where the code behind this advice? – user3069232 Jul 31 '17 at 06:38
  • @VinuDavidJose having classes conform to protocols – rolling_codes Jan 03 '19 at 20:52