2
func callFunctionName(parameters: String) -> returnType
{
    var somevalue = parameters
    var returnValue = somevalue()

    return returnValue
}

Is there a way to take in a input and use it as a function name?

example: let say input is green, I want to call function green. if input is red call function red etc...

Or to have a huge if statement to check each input to call different functions

5 Answers 5

2

This is not possible in Swift. You will have to store any functions you want to call in your own dictionary, and then use that to look up functions by name.

A "huge statement" might be feasible for a small number of functions, and it would certainly perform faster, but the ideal approach would be to store them in a dictionary.

However, if you are dealing with objects:

if exampleObject.respondsToSelector("exampleFunction")
{
    exampleObject.performSelector("exampleFunction")
}

This approach currently works with all classes, be it Objective-C or Swift.

Sign up to request clarification or add additional context in comments.

Comments

1

This is easily possible in Objective-C by using:

[self performSelector:NSSelectorFromString(@"green")];

But Swift is less dynamically typed than Objective-C and has less support for reflection. The Objective-C way I described above is very prone to crashes at runtime if the input (e.g. "purple" if you didn't have a function for purple) doesn't match a function that exists.

Using a big if statement is not an unreasonable way to approach it.

3 Comments

-performSelector is now available in Swift as well :)
Didn't see they had added it! I still like your dictionary approach assuming we're talking about functions
The interesting this is that it even works for pure Swift classes. Upon introspection, one can see that every 'pure' class inherits from a base SwiftObject class, which provides methods such as -performSelector, probably for the runtime to use.
0

As the other answers said, an if statement is probably the best way to go about this.

override func viewDidLoad() {

if someValue = green {
green() //This will run whatever you have in the green() function below
}

}

func green() {
//put code for output of green here
}

Then all you have to do is make separate functions for all your outputs such as the green() func

Comments

0

This is the closest I could get. (And it's partially based on the answer of Vatsal Manot)

The idea is to use closures.

First of all we define the return type of the closure: let's use Int (of course you can change this later).

typealias colorClosureReturnType = Int

Now lets define the type of a closure that receives no parameters (you can change this too) and returns colorClosureReturnType

typealias colorClosureType = () -> (colorClosureReturnType)

Fine, now lets create a dictionary where the key is a String and the value is a closure of type colorClosureType:

let dict : [String: colorClosureType] = [
    "red": { return 0 /* you can write here all the logic you need */ },
    "green": { return 1 /* also here */},
    "blue": { return 2 /* and here */}
]

Usually I let Swift Type Inference to infer the type of the variable/constant. But this time for sake of clarity I explicitly declared the type of the dictionary.

Now we can build a simple function that receives a String and return an optional colorClosureReturnType.

func callClosure(colorName: String) -> colorClosureReturnType? {
    return dict[colorName]?()
}

As you can see the function look in the dictionary a closure associated to the key received as param. If it does found it then runs the closure and returns the results.

If the dictionary does not contain the requested key then the function returns nil. That's why the return type of this function is colorClosureReturnType? and not colorClosureReturnType.

Finally some tests:

callClosure("red") // 0
callClosure("green") // 1
callClosure("blue") // 2

Comments

-1
func callFunctionName(parameters: String) -> ()
{
   _ = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:  Selector(parameters), userInfo: nil, repeats: false)

}
func green() {

}

1 Comment

This is neither Objective-C nor Swift code. Also, this approach has already been detailed in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.