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

Swift 5中在UIAlertController的completion块添加Timer报错求助

问题解决:Cannot convert value of type 'Timer' to expected argument type '(() -> Void)?'

错误原因

present(_:animated:completion:)方法的completion参数要求传入一个可选的无参无返回值闭包((() -> Void)?),但你直接把Timer.scheduledTimer()的返回值(Timer类型实例)传进去了,类型完全不匹配,因此触发报错。

修正后的代码

func showAutoHideAlert() {
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
    present(alertController, animated: true) {
        // 在completion闭包内部创建并启动Timer
        Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) { _ in
            self.dismiss(animated: true, completion: nil)
        }
    }
}

补充优化

如果需要避免循环引用风险,可以添加[weak self]捕获列表:

func showAutoHideAlert() {
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
    present(alertController, animated: true) { [weak self] in
        Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) { _ in
            self?.dismiss(animated: true, completion: nil)
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:25:18