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

Swift开发:不使用结构体/类时如何在UIViewController回调传多个变量

iOS Swift 无需结构体/类实现completion回调回传多变量解决方案

你遇到的报错核心原因是原有completion闭包的参数类型定义与实际传入的参数类型不匹配:你原来定义的completion仅接收Int?类型的单参数,但尝试传入包含两个值的元组,编译器会直接报类型不匹配错误。以下两种方案都不需要额外定义结构体或类,可直接实现需求:


方案1:使用多参数闭包(更简洁直观)

第一步:修改EditTimerViewController的completion定义

把原有代码

public var completion: ((Int?) -> Void)?

修改为

public var completion: ((_ duration: Int?, _ timerName: String?) -> Void)?

第二步:修改EditTimerViewController的savePressed调用逻辑

@IBAction func savePressed(_ sender: UIButton) {
    // 直接传入两个参数调用闭包
    completion?(duration, timerNameField.text)
    self.dismiss(animated: true, completion: nil)    
}

第三步:修改TimerViewController中completion的接收逻辑

destinationVC.completion = { [weak self] duration, timerName in
    DispatchQueue.main.async {
        // 可选绑定避免强制解包闪退
        guard let self = self, 
              let duration = duration, 
              let timerName = timerName else { return }
        self.myTimer.totalTime = Double(duration)
        self.myTimer.timerName = timerName
        self.timerLabel.text = timerName
        // 需要更新时间显示的话自行补充对应label赋值
        self.timer.invalidate()
    }
}

方案2:使用命名元组作为单参数(符合你最初的尝试思路)

第一步:修改EditTimerViewController的completion定义

把原有代码

public var completion: ((Int?) -> Void)?

修改为

// 定义参数为带命名的元组类型
public var completion: (( (duration: Int?, name: String?) ) -> Void)?

第二步:修改EditTimerViewController的savePressed调用逻辑

@IBAction func savePressed(_ sender: UIButton) {
    let timerData = (duration: duration, name: timerNameField.text)
    completion?(timerData)
    self.dismiss(animated: true, completion: nil)    
}

第三步:修改TimerViewController中completion的接收逻辑

destinationVC.completion = { [weak self] timerData in
    DispatchQueue.main.async {
        // 可选绑定避免强制解包闪退
        guard let self = self, 
              let duration = timerData.duration, 
              let name = timerData.name else { return }
        self.myTimer.totalTime = Double(duration)
        self.myTimer.timerName = name
        self.timerLabel.text = name
        self.timer.invalidate()
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:15:04