[swift-users] What is the better way to override KeyedDecodingContainer.decode ?

Solli Honorio shonorio at gmail.com
Mon Oct 23 06:05:56 CDT 2017


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171023/e7b00ae0/attachment.html>


More information about the swift-users mailing list