carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
727 stars 41 forks source link

Issue with subscript not existing causing crash #65

Open jhoughjr opened 2 years ago

jhoughjr commented 2 years ago

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 commented 2 years ago

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

j[optional: "script"]?.string

Would that work for you?

carson-katri commented 2 years ago

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 commented 2 years ago

it should. im guessing the server just didnt encode that part.

I had just ran my app in catalyst so it was in a state it had not previously been in but kinda suprised as this is the first time seeing it and the state i expected it to be in, should have occurred before. Though the cause is the server it seems like something to catch

Sent from my iPhone

On Apr 19, 2022, at 4:08 PM, Carson Katri @.***> wrote:

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

struct SomeData : Codable { let script: String? } AnyRequest { ... } .onObject { someData in $script.wrappedValue = someData.script } — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.

jhoughjr commented 2 years ago

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