Devarshi
Devarshi

Reputation: 16758

Dynamically performing an action based on string passed in textfield

Say I have a textfield - inputTextFieldand a button on UI with action performActionDynamically, in same class I define two functions: 1. firstFunc, 2. secondFunc, now I want to achieve this behavior:

If user types "firstFunc" in textfield and then he taps on button it should invoke firstFunc function, and if he types "secondFunc" in textfield and then he taps on button it should invoke secondFunc function.

In objective-c I would have easily achieved it by following below pseudocode:

  1. Within performActionDynamically pass inputTextField.text in NSSelectorFromString() to obtain selector
  2. Invoke performSelector:withObject: on self to perform respective function

The only thing which I can think in implementing same behavior in swift is -

  1. Define two closures with name firstFunc, secondFunc
  2. Store the closures in a dictionary as values for keys - 'firstFunc' and 'secondFunc' respectively
  3. Obtain respective closure from dictionary based on value in textfield
  4. Invoke obtained closure

Is there any better way to achieve intended behavior? Please guide.

Upvotes: 1

Views: 114

Answers (1)

Oliver
Oliver

Reputation: 566

You could try something like this:

if self.respondsToSelector(Selector(selectorString)) {
    NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0), target: self, selector: Selector(inputTextField.text), userInfo: nil, repeats: false)
}

This is done as a callback, so you will have to take that into account.


You could use NSThread instead of NSTimer if you prefer:

NSThread.detachNewThreadSelector(Selector(inputTextField.text), toTarget: self, withObject: nil)

Upvotes: 1

Related Questions