|
I feel like I've seen the answer to this somewhere but I can't type the right keywords to get to it. Because of this, I suspect that I'm also doing it wrong, and There's A Better Way. I'm writing an application to build passes for Apple Wallet. There are four kinds of passes: boarding passes, payment methods, coupons, and "generic". They all have some common fields, and then each one has special rules. I'm trying to make some helper structs that will make generating valid JSON for the Deep inside, there are fields (things like title, heading, etc.) that can take one of three data types: a plain Then, a pass can have collections of fields: the stuff on the back, the header, the front, auxiliary. Each of these is a So, what does that mean? Do I have to do this with classes and inheritance rather than protocols? |
|
You can't supply a protocol as the type to decode into, it has to be a concrete type. Which, as you've encountered, can be a problem when there are multiple types involved. If you give us some sample code (structs, JSON data, etc.) we can work on a solution. Also, maybe this article will be some help: Bringing Polymorphism to Codable |
|
|
|
I mean, it's possible with structs, it just depends on how your JSON is structured and what your structs look like. Here's an example:
(example inspired by Encoding And Decoding Polymorphic Objects In Swift) You could also use an enum-based solution. |
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.
Link copied to your pasteboard.