Swift:静态函数内调用alertTheUser函数报错‘extra argument in call’求助
解决静态函数中调用弹窗函数报错「extra argument in call」的问题
嘿,我来帮你搞定这个弹窗调用的问题!你遇到的「extra argument in call」报错,结合你说的场景(在静态函数里调用alertTheUser),大概率是实例方法和静态方法的调用权限问题,当然也有可能是参数传递的小失误,我给你拆解下解决方案:
核心问题分析
你定义的alertTheUser如果是普通的实例方法(没有加static或class关键字),那它只能被这个类的实例对象调用。而你的fetchUser是静态函数(带static/class关键字),它属于类本身,不能直接调用实例方法——这就会导致调用时的参数匹配报错(本质是找不到对应的静态方法签名,编译器误判为参数多余)。
具体解决方案
方案1:把弹窗函数改成静态方法
如果你的弹窗不需要依赖类的实例变量,直接把alertTheUser改成静态方法,这样就能在静态的fetchUser里直接调用了:
static func alertTheUser(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) // 注意:静态方法里需要手动获取顶层ViewController来弹窗 if let topViewController = UIApplication.shared.windows.first?.rootViewController?.presentedViewController ?? UIApplication.shared.windows.first?.rootViewController { DispatchQueue.main.async { topViewController.present(alert, animated: true, completion: nil) } } }
额外提醒:网络请求(比如你的
fetchUser)是异步的,弹窗必须在主线程执行,所以一定要包在DispatchQueue.main.async里!
方案2:在静态函数中获取类的实例再调用
如果alertTheUser必须是实例方法(比如依赖类里的某些实例属性),那你需要在静态的fetchUser里拿到这个类的实例对象,再调用弹窗:
// 假设你的静态fetchUser在YourViewController类里 static func fetchUser() { // ...你的用户获取逻辑,当longitude为nil时 DispatchQueue.main.async { // 获取当前显示的ViewController实例 if let currentVC = UIApplication.shared.windows.first?.rootViewController as? YourViewController { currentVC.alertTheUser(title: "提示", message: "经度信息为空,请检查") } } }
小概率排查:参数传递错误
如果上面两种情况都不是,那检查下你调用alertTheUser的时候是不是多传了参数?比如写成了alertTheUser(title: "xx", message: "yy", extra: "zz"),而函数定义只有两个参数,也会触发这个报错。
内容的提问来源于stack exchange,提问作者user9043410
相关产品推荐
相关产品推荐

