-1

In JavaScript you can dynamically call a method like this:

class Foo {
  myMethod() {
    console.log('myMethod')
  }
}

var foo = new Foo()
var method = 'myMethod'
foo[method]()

You can write the method as a string and dynamically call it. You can also do this:

foo[method].apply(someScope, [ argA, argB, ... ])

Wondering if you can do anything like this in Swift, I am new to swift.

Lance
  • 75,200
  • 93
  • 289
  • 503
  • 3
    When you are trying to dynamically call methods in a strongly typed, compiled language, you are most probably on the wrong track to solve your issue. This is especially true for Swift. Explain the problem you're trying to solve that you think requires having to dynamically all methods, rather than trying to translate JS code line by line to Swift. – Dávid Pásztor Mar 14 '19 at 09:18
  • Well, [`Objective C` surely did allowed this](https://developer.apple.com/documentation/objectivec/1456712-objc_msgsend), and if you can just limit yourself to code(classes) created in `ObjC` (and bridged to `Swift`) you can do this. – user28434'mstep Mar 14 '19 at 09:21
  • 1
    isn't that what KVO for ? – Mohmmad S Mar 14 '19 at 09:25

1 Answers1

-1

You can use KVO pattern to solve this issue, however as @David Pasztor comment says.

When you are trying to dynamically call methods in a strongly typed, compiled language, you are most probably on the wrong track to solve your issue. This is especially true for Swift. Explain the problem you're trying to solve that you think requires having to dynamically all methods, rather than trying to translate JS code line by line to Swift.

However KVO can be used to solve such issues, i suggest reading about it it allows you to dynamically observe keys, and based on that you can do your actions.

Keep in mind KVO is compiled with Ojbc compiler.

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • Actually, `KVO` is not needed here, i mean `bserving part`. Just [`selector`s](https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3) will do. – user28434'mstep Mar 14 '19 at 09:34
  • 2
    How is KVO related to dynamically calling methods? KVO can be used to execute methods when the value of an observed variable/property changes, but those methods still need to be strongly typed. KVO is completely unrelated to OP's question. – Dávid Pásztor Mar 14 '19 at 09:35
  • it can be used to execute strongly typed functions, if he observed some values , just alternative solution . – Mohmmad S Mar 14 '19 at 09:37
  • looking at his case he is probably trying to execute functions base on actions at the run time, so observing keys could be helpful for him to achieve that, i am not saying this is the ultimate answer for his question, it could be helpful and work for him. @DávidPásztor please note something for me i can learn, about this topic – Mohmmad S Mar 14 '19 at 09:40