I have a need to extend struct
having failable initializer with a throwing initializer calling that failable initializer. And I see no elegant or clear way to do that in Swift 3.1.
Something like this:
extension Product: JSONDecodable {
public enum Error: Swift.Error {
case unableToParseJSON
}
init(decodeFromJSON json: JSON) throws {
guard let jsonObject = json as? JSONObject else {
throw Error.unableToParseJSON
}
// Meta-code
self.init(dictionary: jsonObject) ?? throw Error.unableToParseJSON
}
}
Is there an elegant and clean way to do that?
Found a semi-clean way to do that while writing the question:
extension Product: JSONDecodable {
public enum Error: Swift.Error {
case unableToParseJSON
}
init(decodeFromJSON json: JSON) throws {
guard let jsonObject = json as? JSONObject,
let initialized = Self(dictionary: jsonObject)
else {
throw Error.unableToParseJSON
}
self = initialized
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With