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

Swift/Combine中如何从Timer.publish向方法传递两个参数

解决方案

要实现每个计时器实例的计数与名称绑定并存入字典,核心是把实例名称和计时器计数一起传递到接收闭包中,以下是修改后的代码:

import Combine
import Foundation

var subscriptions = Set<AnyCancellable>()
var dict = [String: Int]() // 建议用原生Swift字典替代NSMutableDictionary

func multiplecall(name: String) {
    Timer.publish(every: 1, on: .main, in: .common)
        .autoconnect()
        .scan(1) { value, _ in value + 1 }
        .map { (name, $0) } // 将实例名称与计数打包成元组
        .sink(receiveValue: { testName, ticker in
            dict[testName] = ticker
            print(dict) // 打印验证结果,格式如["test1":1, "test2":1]、["test1":2, "test2":2]
        })
        .store(in: &subscriptions)
}

// 调用示例
multiplecall(name: "test1")
multiplecall(name: "test2")

修改说明:

  • 修正subscriptions的类型为Set<AnyCancellable>,符合Combine的类型要求
  • 用原生Swift字典[String: Int]替代NSMutableDictionary,更符合Swift语法习惯
  • 通过map操作将实例名称name和计时器计数$0打包成元组,这样就能把名称传递到后续的接收闭包中
  • 在sink的闭包里直接完成字典赋值,无需单独定义fetchValues函数(如果需要保留fetchValues,也可以改成接收元组参数后调用)

如果要保留你期望的fetchValues函数,可调整如下:

func fetchValues(testName: String, ticker: Int) {
    dict[testName] = ticker
    print(dict)
}

// 在multiplecall的sink中调用:
.sink(receiveValue: { fetchValues(testName: $0.0, ticker: $0.1) })

这样每个计时器触发时,都会更新对应名称的计数,最终字典会按你期望的格式动态更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:05