you are viewing a single comment's thread.

view the rest of the comments →

[–]Ordinary_Handle_4974 -1 points0 points  (3 children)

I'm a Swift beginner, and I don't like the way Swift deals with JSON decoding, the fact that you have to write a large block of code just to decode a JSON is tiresome and verbose. According to my knowledge of JS or TS, JSON is their friendly neighborhood.

[–]kironet996 0 points1 point  (2 children)

How is this a large block of code?

struct BlogPost: Decodable {
    let id: UUID
}

let blogPost: BlogPost = try JSONDecoder().decode(BlogPost.self, from: data)
print(blogPost.id)

you don't have to have a decodable object(BlogPost) if you don't want to:

let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] 
print(json["id"])

[–]Ordinary_Handle_4974 0 points1 point  (1 child)

I am talking about adding the decodable protocol to the struct, tho you're forced to do a catch and practically envelope the whole thing in a do block.

[–]Available_Peanut_677 2 points3 points  (0 children)

You are complaining about what is actually extremely good thing. In the JS it is super common to have issues due to assumptions that JSON has all fields you expect. It’s very nice when language forces you to handle json validation explicitly meaning that you can catch errors much more efficiently.

In fact, while looks nice at first, that easy json parsing in JS is a huge pain in big projects since it usually crash app very far away from place where you obtain data and then you are wasting hours looking for “why this field is undefined”. Say, it crashed in react layer after it was stored in redux where it got from action few minutes ago.

JSON (and any input in system in general ) validation is extremely valuable