Reputation: 2937
I need advice on the best approach I should take.
I have lots a data from a server I need to parse in convert into structs.
So let's say I am getting seller
information from a server, the struct might look like this:
struct Seller {
var firstName: String?
var lastName: String?
var address: String?
}
I have created a protocol for this and made my seller struct adopt it. So my code now looks like this:
protocol SellerProtocol {
var firstName: String {get set}
var lastName: String {get set}
var address: String {get set}
}
extension Seller: SellerProtocol {
var firstName: String?
var lastName: String?
var address: String?
}
Question: is there a way to make all of the variables in this protocol non-optional dynamically?
The thing is, I have many such optional protocols but, I also need to declare a non-optional version of the exact same protocol so that other classes can conform to it. I only want the structs that interact directly with the server to be of optional type (because the data from server can contain nils), but after I process the information from the server, I want to create a non-optional structure.
So do I need to maintain two versions of the exact same protocol? An optional version, and a non-optional version?
Upvotes: 1
Views: 351
Reputation: 7400
What you want to do is to declare the protocol as non-optional, then use a failable initializer to create your struct. That way, if you're missing certain properties, object initialization will fail, but if initialization succeeds, you have all the data you need.
You can reference this link if you need help creating a failable initializer.
Upvotes: 1
Reputation: 13679
No, there isn't a way to dynamically change a protocol's required properties / methods or the types used therein. Protocols are contracts that the compiler needs to be able to consider invariant in order to analyze and validate your code. Changing a protocol (or what protocols a type conforms to) at runtime would essentially break the contracts you promised to the compiler at build time.
It seems to me that your SellerProtocol should not include optionals if a seller is absolutely expected to have those properties within your application. At the point where you are getting data from the server, why is it required that a transient / temporary representation of possibly nil data conform to that protocol at all? It seems like only if the data is not nil / missing would you then populate a SellerProtocol-conforming type with it.
Upvotes: 1