Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Failables? #11

Closed
umairsuraj opened this issue Jan 9, 2020 · 1 comment
Closed

Support for Failables? #11

umairsuraj opened this issue Jan 9, 2020 · 1 comment

Comments

@umairsuraj
Copy link

let json = """ [ {"name": "Taro", "age": 20}, {"name": "Hanako"} ] """.data(using: .utf8)! // Hanako has no "age"

@marksands
Copy link
Owner

I'm not sure what you're expected behavior is. Would you want to silently fail "Hanako", or would you want the parsing to throw?

There's a @LossyArray type that you can use, if your data has a root key. If the array is the root then you can use LossyArray as the decodable type.

let json = #"[ {"name": "Taro", "age": 20}, {"name": "Hanako"}]"#.data(using: .utf8)! // Hanako has no "age"

struct NameAndAge: Codable {
    let name: String
    let age: Int
}

let results = try JSONDecoder().decode(LossyArray<NameAndAge>.self, from: json)
print(results.wrappedValue) // [{ name: "Taro", age: 20 }]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants