WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Cupcake Corner - Am I Understanding Codable Correctly?

Forums > 100 Days of SwiftUI

The final challenge of cupcake corner is to move the order details to a struct and wrap the struct in a class.

class SharedOrder: ObservableObject {
    @Published var data = Order()
}

struct Order: Codable {
// all variables previously in the class
}

However, we don't need to write custom encoding for the variables in the struct. This is because all of the data types (Bool, String, Double) inside the struct automatically conform to the conform to the codable protocol.

My questions:

  1. Am I understanding the reasoning correctly? (Please correct me if I am not)
  2. Why does Paul keep static let types = ["Vanilla", "Strawberry", "Chocolate", "Rainbow"] inside the class?
  3. Why does Paul keep the CodingKeys enum inside the struct if we're not using them for a custom encoder?
  4. What data types in structs would NOT conform to codable and would require a custom function to encode the data?

Encoding/decoding has been a challenging topic for me. I appreciate any guidance with this!

1      

@iospIT asks:

What data types in structs would NOT conform to codable and would require a custom function to encode the data?

I think in another project you tap locations on a map of places you'd like to visit. These are processed as core locations in the struct, that is they are CLLocation objects with latitude and longitude. While CLLocations are great with maps, they cannot be turned encoded into JSON data. Consequently, you'll see that @twostraws introduces a clever way to use one data type to encode and store, and uses another to use in MapKit.

1      

Please note: As a HWS+ member you get to see @twostraw's challenge solution.

Some Many of us don't have those resources. That is, we can't see how @twostraws wrapped an Order struct within a CakeOrder class. Perhaps this would be a good question in the "members only" forum?

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.