Search code examples
jsonswiftjsondecoder

Swift Decode JSON Response to GMSCoordinateBounds Array


In my app I have the following JSON response and struct which represent the Active working areas

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
}

Struct :

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
    }
    
}

after decoding the response i need to check if the user current location is within the Active bounds and this is very easy using GMSCoordinateBounds.contains(latLong) so how i can just decode and initials it directly in my ActiveBounds struct to return the data property as array of GMSCoordinateBounds instead of LatLngBounds struct

This is what Im want to accomplish

import Foundation
import CoreLocation
import GoogleMaps

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

Solution

  • No need to write ! at the end of your properties...

    The easier way, is do make a lazy var or a computed property on ActiveBounds where it will transform [LatLngBounds] into a [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) }
        }()
    }
    

    That way, you don't "alterate" your JSON model needing custom init(from decoder:).