Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Annegret Heimerzheim
Annegret Heimerzheim
3,190 Points

call a method who's name is contained in a variable

I have a list of method names and associated parameters which the user has configured to be executed one after another. How can I call these methods? I'm coming from the Microsoft .net world. There is a 'callbyName' command to which I can pass the function name and the parameters. I think this should be possible in iOS (Swift?) as well. Does Treehouse offer a course covering this topic or can you give me a hint where to look for an answer? Thank you very much Annegret

3 Answers

Nathan F.
Nathan F.
30,773 Points

I'm not familiar at all with call-by-name but a quick Google search turns this up, which may help?

Annegret Heimerzheim
Annegret Heimerzheim
3,190 Points

Thanks, Nathan, but the link is about function parameters.

Stone Preston
Stone Preston
42,016 Points

in Objective C this is known as a selector. You can read about them here.

As far as implementing a selector in Swift, give this stack overflow post a read

Looks like it may be a bit different than it was in Objective C, but looking at some of the answers in that post its still easy to do in Swift

I may be wrong, but allowing a user to to provide names of methods to call and giving the user a lot of control over code like that does not sound like a very good idea to me. It might be a good idea to look into some alternative ways of achieving your goal