Decode Bool from Int or String
Swift
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
}
}