0

As we know a string object have methods like uppercased, lowercased, capitalise.

I want to call selector at run time. For ex:

let aSelector = Selector("capitalise")

let str = "Good Morning"
//now i want to apply aSelector on str:
let finalString = str.aSelector

How can i achieve it? Thanks.

3
  • How would you use this? Commented Aug 2, 2018 at 0:18
  • I have two constants file for two target. In these files i want to define selector let's say capitalise and uppercase. Now in my code which is common to both targets, I have a string it can be capitalise or uppercase, without any if else. ex : str.thatSelectorInMyConstantFile @vacawama Commented Aug 2, 2018 at 0:30
  • If you want a better answer, you'll want to explain exactly what problem you're trying to solve, rather than how you're trying to solve it. Commented Aug 2, 2018 at 0:58

2 Answers 2

2

I have two constants file for two target. In these files i want to define selector let's say capitalise and uppercase. Now in my code which is common to both targets, I have a string it can be capitalise or uppercase, without any if else. ex : str.thatSelectorInMyConstantFile

How about using a closure:

let stringOp = { (str: String) in str.capitalized }

OR

let stringOp = { (str: String) in str.uppercased() }

Then you'd use it like:

let str = "hello world"
let finalString = stringOp(str)
print(finalString)

Output:

Hello World

OR

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

Comments

0

You can only call selectors on objects that inherit from NSObject, so you would not be able to use a selector on a string.

In general, you are able to do: object.perform(#selector(ViewController.mySelectorMethod))

But you should explain what you are trying to achieve - selectors aren't used in the way you've described, and there is probably a more standard implementation of what you're aiming for.

1 Comment

I have two constants file for two target. In these files i want to define selector let's say capitalise and uppercase. Now in my code which is common to both targets, I have a string it can be capitalise or uppercase, without any if else. ex : str.thatSelectorInMyConstantFile

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.