|
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. |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.