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

Swift如何将JSON响应直接解码为GMSCoordinateBounds数组

实现方案

因为GMSCoordinateBounds未默认遵从Codable协议,所以需要手动实现ActiveBounds的解码初始化方法,先解析data数组里的原始坐标参数,再直接构造GMSCoordinateBounds实例赋值给data属性即可,完整实现代码如下:

import Foundation
import CoreLocation
import GoogleMaps

struct ActiveBounds : Codable {
    var status_code : Int!
    var data : [GMSCoordinateBounds]!
    var message : String!
    
    // 手动指定编码解码键
    enum CodingKeys: String, CodingKey {
        case status_code, data, message
    }
    
    // 手动实现解码初始化逻辑
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 解码基础字段
        status_code = try container.decode(Int.self, forKey: .status_code)
        message = try container.decodeIfPresent(String.self, forKey: .message)
        
        // 定义临时结构体承接接口返回的原始坐标数据,仅在当前初始化方法内生效
        struct TempBounds: Codable {
            var name : String
            var north_east_lat : CLLocationDegrees
            var north_east_lng : CLLocationDegrees
            var south_west_lat : CLLocationDegrees
            var south_west_lng : CLLocationDegrees
        }
        let tempBoundsList = try container.decode([TempBounds].self, forKey: .data)
        
        // 批量转换为GMSCoordinateBounds实例
        data = tempBoundsList.map { temp in
            let northeast = CLLocationCoordinate2D(latitude: temp.north_east_lat, longitude: temp.north_east_lng)
            let southwest = CLLocationCoordinate2D(latitude: temp.south_west_lat, longitude: temp.south_west_lng)
            return GMSCoordinateBounds(coordinate: northeast, coordinate: southwest)
        }
    }
}

补充说明:如果后续业务需要保留每个区域的name标识,可将data属性定义为[(name: String, bounds: GMSCoordinateBounds)]类型,在map转换时同时返回name和构造完成的bounds对象即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:12:03