Decode Bool from Int or String

Swift

Because, you know, sometimes the backend guys send us a 1 or TRUE and expect us to map it to native Bool object, well, they are kinda right, it shouldn't matter that much

swift

public extension KeyedDecodingContainer where Key: CodingKey { public func decodeBoolAsIntOrString(forKey key: K) throws -> Bool { if let bool = try? decode(Bool.self, forKey: key) { return bool } if let bool = try? decode(String.self, forKey: key) { return bool == "1" } let int = try decode(Int.self, forKey: key) return int == 1 } public func decodeBoolAsIntOrStringIfPresent(forKey key: K) throws -> Bool? { if let bool = try? decodeIfPresent(Bool.self, forKey: key) { return bool } if let bool = try? decodeIfPresent(String.self, forKey: key) { return bool == "1" } if let int = try? decodeIfPresent(Int.self, forKey: key) { return int == 1 } return nil } }