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
相关产品推荐
相关产品推荐

