MichaelB
MichaelB

Reputation: 394

Swift Decoding Plist Dictionary of Dictionaries

I'd like to use a property list decoder to decode a binary plist of dictionaries

Dictionary

Object that makes dictionary:

struct ZipCode: Codable {

    var zipCode: String
    var city: String
    let state: String
    let latitude: String
    let longitude: String
    let timezone: String
    let daylightSavingsFlag: String
    let geopoint: String

    enum CodingKeys: String, CodingKey {
        case zipCode = "Zip"
        case city = "City"
        case state = "State"
        case latitude = "Latitude"
        case longitude = "Longitude"
        case timezone = "Timezone"
        case daylightSavingsFlag = "Daylight savings time flag"
        case geopoint = "geopoint"
    }   
}

Wrapper object:

struct ZipCodeList: Codable {

    var zipCodes: [String:ZipCode]

}

Me trying to read it in which results in nil zipCodelist:

do {
           let path        = Bundle.main.path(forResource: "ZipCodes", ofType: "plist")
           let binary         = FileManager.default.contents(atPath: path!)
           let zipCodes = try? PropertyListDecoder().decode(ZipCodeList.self, from: binary!)
           print("Hi")
    } catch {

}

Upvotes: 1

Views: 1177

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51973

Your plist doesn’t have an element zipCodes as a root element, instead decode as

let zipCodes = try? PropertyListDecoder().decode([String: ZipCode].self, from: binary!)

Upvotes: 3

Related Questions