Codable is great and I'm moving to it, but sometimes server return numbers as a string and I have to force the parser to take care of this behavior.
I would like your opinion if this is the better solution to parse numbers even when I got string. Thanks, Solli Honorio <code> import Foundation extension KeyedDecodingContainer { public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let stringValue = try? self.decodeIfPresent(String.self, forKey: key) else { return try self.decode(Int.self, forKey: key) } guard let integerValue = Int.init(stringValue!) else { return try self.decode(Int.self, forKey: key) } return integerValue } public func decodeIfPresent(_ type: Int.Type, forKey key: K) throws -> Int? { guard let stringValue = try? self.decodeIfPresent(String.self, forKey: key) else { return try self.decodeIfPresent(Int.self, forKey: key) } guard let integerValue = Int.init(stringValue!) else { return try self.decodeIfPresent(Int.self, forKey: key) } return integerValue } } let jsonString = """ { "id": "1", "string": "string", "integer": "42", "type": "locations", "boolean": true } """ let jsonData = jsonString.data(using: .utf8)! struct JSONEntity: Codable { let id: Int? let string: String let integer: Int let type: String let boolean: Bool } let decoder = JSONDecoder() let foo = try! decoder.decode(JSONEntity.self, from: jsonData) debugPrint(foo)</code> -- "o animal satisfeito dorme". - GuimarĂ£es Rosa
_______________________________________________ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users