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

如何访问Swift中尾随闭包内switch case的关联值

learningList 是.success分支模式匹配时绑定的局部变量,作用域仅限制在当前 .success case 的代码块内,你直接替换原代码里的break语句,在该代码块内编写操作learningList的逻辑即可。

示例代码如下:

_ = query.find { result in
    switch result  {
    case .success(objects: let learningList):
        // 此处可直接访问learningList,示例逻辑如下:
        print("查询成功,共获取\(learningList.count)条数据")
        // 遍历数据示例
        for learningItem in learningList {
            print(learningItem)
        }
    case .failure(error: let error):
        print(error)
    }
}

额外说明:

  • 如果你需要在find方法的闭包外部使用learningList的内容,需要在闭包外层提前定义变量用来存储该值,同时注意闭包的强引用捕获规则,避免出现循环引用问题。
  • learningList的具体类型由query对应的查询模型决定,你可以根据实际业务场景调用对应类型的属性和方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:57:03