UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: CupcakeCorner URLSession forcing me to unwrap 'data' optional

Forums > 100 Days of SwiftUI

So one of the challenges in the CupcakeCorner wrap up section states:

If our call to placeOrder() fails – for example if there is no internet connection – show an informative alert for the user. To test this, just disable WiFi on your Mac so the simulator has no connection either.

And the code that Paul provided looked something like this:

URLSession.shared.dataTask(with: request) { data, response, error in
            if let decodedOrder = try? JSONDecoder().decode(Order.self, from: data) {
                self.confirmationMessage = "Your order for \(decodedOrder.quantity)x \(Order.types[decodedOrder.type].lowercased()) cupcakes is on its way!"
                self.showingConfirmation = true
            } else {
                print("Invalid response from server")
            }
        }.resume()

The problem is, the code above actually does not work for me. Particulary, Xcode does not like the second line if let decodedOrder = try? JSONDecoder().decode(Order.self, from: data). It pushed me to rewrite the line to, if let decodedOrder = try? JSONDecoder().decode(Order.self, from: data!) using forced unwrapping. So naturally, when I go to turn off the internet connection and place an order when trying to complete the challenge question, the app crashes and burns due to a nil value being discovered.

Did anyone else have a similiar problem to this? I've attempting trying to solve it using nil coalescing, but Swift doesnt like that either since 'String' and 'data' and two different types.

Thank you for taking the time to read this far! I really appreciate this community

2      

You forgot the part where that code is wrapped in an if let in order to get the unwrapped Optional...

You need it to be like this:

URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        //now you can do your decoding because data is no longer an Optional
    }
}.resume()

3      

My god, thanks for the help, can't believe I missed it

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.