使用Selector时遇类型转换错误,求Swift4(Xcode9.0)解决方案
Hey there, I’ve run into this exact issue back when Swift 4 launched—let’s break down what’s going on and how to fix it quickly.
Why this error happens
The error is telling you that you’re trying to pass a closure (() -> ()) where a Selector is required. In Swift 4, Selector is tied to Objective-C-exposed methods, and you can’t directly use a closure in place of one. A common mistake here is trying to pass inline closure code instead of referencing a proper method.
Step-by-step fixes
Mark your target method with
@objc
Swift 4 stopped automatically exposing Swift methods to Objective-C by default. So if you’re using a custom method, you need to add the@objcmodifier to make it accessible forSelector:@objc func handleButtonTap() { // Your button action logic here }If your class inherits from
NSObject(likeUIViewControllerorUIView), this is all you need for the method to be visible to Objective-C. If it’s a pure Swift class, you’ll also need to make it inherit fromNSObjector use@objcMemberson the class to expose all methods.Use
#selector()to reference your method
Replace that closure with the#selector()syntax that points to your method. For example, when adding a target to a button:myButton.addTarget(self, action: #selector(handleButtonTap), for: .touchUpInside)If your method takes parameters (like a sender), make sure to include the parameter label in the selector:
@objc func handleButtonTap(_ sender: UIButton) { // Logic with sender } // Then reference it as: #selector(handleButtonTap(_:))Avoid passing closures directly
The wrong code that triggers this error usually looks like this:// ❌ This will throw the error you're seeing myButton.addTarget(self, action: { self.handleButtonTap() }, for: .touchUpInside)Ditch the closure and use the
#selectorapproach instead.
内容的提问来源于stack exchange,提问作者Kion

