快速解码对 GMSCoordinateBounds 数组的 JSON 响应

阿里阿迪尔 |

在我的应用程序中,我有以下代表活动工作区的 JSON 响应和结构

JSON :

{
    "status_code": 1000,
    "data": [
        
        {
            "name": "BWME23DW",
            "north_east_lat": 33.34534,
            "north_east_lng": 44.56467
            "south_west_lat": 34.89434,
            "south_west_lng": 44.54567

        },
    ],
    "message": null
}

结构:

import Foundation
import CoreLocation
import GoogleMaps

struct ActiveBounds : Codable {
    
    var status_code : Int!
    var data : [LatLngBounds]!
    var message : String!
}

struct LatLngBounds : Codable{
    
    var name : String!
    var north_east_lat : CLLocationDegrees!
    var north_east_lng : CLLocationDegrees!
    var south_west_lat : CLLocationDegrees!
    var south_west_lng : CLLocationDegrees!
    
    enum CodingKeys: String, CodingKey {
        
        case name
        case north_east_lat
        case north_east_lng
        case south_west_lat
        case south_west_lng
    }
    
}

解码响应后,我需要检查用户当前位置是否在 Active 边界内,这很容易使用,GMSCoordinateBounds.contains(latLong)因此我如何直接在我的 ActiveBounds 结构中对其进行解码和初始化,以将数据属性作为 GMSCoordinateBounds 数组而不是 LatLngBounds 返回结构

这就是我想要完成的

import Foundation
import CoreLocation
import GoogleMaps

struct ActiveBounds : Codable {
    
    var status_code : Int!
    var data : [GMSCoordinateBounds]!
    var message : String!
}
眼泪

无需!在属性末尾...

更简单的方法是ActiveBounds在将转换[LatLngBounds][GMSCoordinateBounds].

struct ActiveBounds : Codable {

    var status_code : Int
    var data: [LatLngBounds]
    var message: String

    lazy var coordinatesBounds: [GMSCoordinateBounds] = {
        data.map { GMSCoordinateBounds(coordinate: CLLocationCoordinate2D(latitude: $0.north_east_lat, 
                                                                          longitude: $0.north_east_lng),
                                       coordinate: CLLocationCoordinate2D(latitude: $0.south_west_lat, 
                                                                          longitude: $0.south_west_lng) }
    }()
}

这样,您就不会“改变”需要 custom 的 JSON 模型init(from decoder:)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章