Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: calling failable initializer from throwing initializer?

Tags:

ios

swift

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?

like image 882
rshev Avatar asked Dec 18 '22 08:12

rshev


1 Answers

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
    }
}
like image 193
rshev Avatar answered Feb 24 '23 17:02

rshev