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

Swift异步函数返回数组赋值为空问题解决方法

问题根因

getCoords是典型的异步函数,传入的闭包是任务完成后的回调,不会阻塞后续代码执行。你写在闭包外的print(weightedList)和heatmapLayer.weightedData = weightedList会在getCoords的耗时任务(比如网络请求、本地数据读取)还没完成、回调还没触发的时候就执行,此时weightedList还没被填充,自然是空数组。

修复方案

所有依赖异步返回结果的逻辑,必须放到回调闭包内部执行,修正后的代码如下:

func assignWeights(){
    var weightedList = [GMUWeightedLatLng]()
    getCoords { [weak self] coords in
        guard let self = self else { return }
        self.coords = coords
        for coord in coords {
            // 修正原代码笔误:遍历单个元素取coord.location,不要用数组对象coords.location
            let lat = Double(coord.location.latitude)!
            let long = Double(coord.location.longitude)!
            let coordinateItem = GMUWeightedLatLng(
                coordinate: CLLocationCoordinate2DMake(lat, long),
                intensity: 2.0
            )
            weightedList.append(coordinateItem)
        }
        // 数组填充完成后再执行赋值、打印操作
        print(weightedList)
        self.heatmapLayer.weightedData = weightedList
    }
}

补充说明

  • 闭包处添加[weak self]是Swift闭包的标准写法,用来避免循环引用导致的内存泄漏。
  • 异步代码的执行顺序不是线性从上到下的,永远不要在异步回调的作用域外,直接读取回调内部才会赋值的变量。如果后续需要在更多地方用到weightedList的结果,可以给assignWeights也增加回调参数,或者使用Swift 5.5+支持的async/await语法改写异步逻辑,避免闭包嵌套。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:27:18