You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selector时遇类型转换错误,求Swift4(Xcode9.0)解决方案

Fixing "Cannot convert value of type '() -> ()' to expected argument type 'Selector'" in Swift 4 (Xcode 9)

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 @objc modifier to make it accessible for Selector:

    @objc func handleButtonTap() {
        // Your button action logic here
    }
    

    If your class inherits from NSObject (like UIViewController or UIView), 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 from NSObject or use @objcMembers on 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 #selector approach instead.

内容的提问来源于stack exchange,提问作者Kion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:29:36