ios - Swift: calling failable initializer from throwing initializer? -
i have need extend struct
having failable initializer throwing initializer calling failable initializer. , see no elegant or clear way in swift 3.1.
something 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 elegant , clean way that?
found semi-clean way while writing question:
extension product: jsondecodable { public enum error: swift.error { case unabletoparsejson } init(decodefromjson json: json) throws { guard let jsonobject = json as? jsonobject, let initialized = type(of: self).init(dictionary: jsonobject) else { throw error.unabletoparsejson } self = initialized } }
Comments
Post a Comment