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

Issue with subscript not existing causing crash #65

Open
jhoughjr opened this issue Apr 19, 2022 · 4 comments
Open

Issue with subscript not existing causing crash #65

jhoughjr opened this issue Apr 19, 2022 · 4 comments

Comments

@jhoughjr
Copy link

jhoughjr commented Apr 19, 2022

Ive stumbled upon a case where my server returned a partially formed body that doesnt include a key.
I see no way in the api to safely access a subscript that may not exist.
Json line 65: json.jsonData = (jsonData as! [String: Any])[s]!

My code:

 .onJson { j in
            print(j)
            if j.stringified?.contains("script") != nil { // added to get around the crash
            $script.wrappedValue = j["script"].string
            } // added
        }

Id expect nil as opposed to a crash. I think thats what js would do, just return undefined for a non existing key instead of treating it as an error.
In my xp, though I use force unwraps , I nearly always end up reverting them.

@carson-katri
Copy link
Owner

Nice catch. I think we could include another subscript like:

j[optional: "script"]?.string

Would that work for you?

@carson-katri
Copy link
Owner

Your other option is to use Codable, which I think is preferable in most cases:

struct SomeData : Codable {
  let script: String?
}
AnyRequest<SomeData> {
  ...
}
.onObject { someData in
  $script.wrappedValue = someData.script
}

@jhoughjr
Copy link
Author

jhoughjr commented Apr 19, 2022 via email

@jhoughjr
Copy link
Author

I usually use coddle but Request had Json baked in so I just used it since it was just a normally two property object.

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