Mika
Mika

Reputation: 13

Swift4 / JSON / Decode

I'm new to Swift 4 and I looked for hours of hours to find a solution for my issue.

import Foundation 

public struct Coin: Codable {
  let name:   String //= "Default"
  let symbol: String
}

open class CoinCapIOAPI {

func fetchMap() {

    let urlString = "http://socket.coincap.io/map"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        // Maybe later...
        guard let data = data else { return }

        do {

            let coins = try JSONDecoder().decode([Coin].self, from: data)
            print(coins)


        } catch let jsonErr {
            print("Error: ", jsonErr)
        }

        }.resume()
   }
}

The JSON looks like:

[
{ aliases: [ ],
name: "300 Token",
symbol: "300",
},
{
aliases: [ ],
name: "SixEleven",
symbol: "611",
},
]

I need just name and symbol. But without the default of name in the struct I get following error:

Error: keyNotFound(CoinBartender.Coin.(CodingKeys in _7C60C6A5E9E301137DE95AF645AB94EB).name, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 91", intValue: Optional(91))], debugDescription: "No value associated with key name (\"name\").", underlyingError: nil))

If I add the default value for "name" I get this result:

[CoinBartender.Coin(name: "Default", symbol: "300"), CoinBartender.Coin(name: "Default", symbol: "611"),

Why does symbol work but name doesn't?

Upvotes: 0

Views: 350

Answers (2)

ridvankucuk
ridvankucuk

Reputation: 2407

Your Coin struct should be like this:

public struct Coin: Codable {
    let name:   String? //= "Default"
    let symbol: String
}

Because some indexes does not contain name.

Upvotes: 0

vadian
vadian

Reputation: 285069

Please read the error message carefully. It's exactly describing the issue:

Error: keyNotFound(CoinBartender.Coin.(CodingKeys in _7C60C6A5E9E301137DE95AF645AB94EB).name, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 91", intValue: Optional(91))], debugDescription: "No value associated with key name (\"name\").", underlyingError: nil))

It says that the 92nd entry (index is zero-based) does not have a key name

{"aliases":[],"symbol":"QTM"} 

One solution is to declare name as optional

let name: String?

Upvotes: 2

Related Questions