- Why can't I just pass the name of the String function to the action?
Using strings for selectors is deprecated, and now you should write #selector(methodName) instead of "methodName" . If the methodName () method does not exist, you will get a compilation error - another class of errors is eliminated during compilation. This was not possible using strings.
- How to implement this correctly after Swift Way? Using the Selector class?
You did it right:
button.addTarget(self, action: #selector(ClassName.methodName(_:)), forControlEvents: UIControlEvents.TouchUpInside)
- Why do we need to pass the @objc keyword and how does it affect the function?
In Swift, the normal approach is to bind method calls and method bodies at compile time (e.g. C and C ++ do). Goal C do this at runtime. Thus, in Objective-C, you can do some things that are not possible in Swift - for example, you can implement a method implementation at runtime (this is called a swizzling method). Cocoa was designed to work with the Objective-C approach, so you need to tell the compiler that your Swift method must be compiled in Objective-C style. If your class inherits NSObject, it will compile in ObjC style, even without the @objc keyword.
source share