Swift 4 JSON Decodable simplest way to decode type change

后端 未结 8 2049
天涯浪人
天涯浪人 2020-12-01 05:47

With Swift 4\'s Codable protocol there\'s a great level of under the hood date and data conversion strategies.

Given the JSON:

{
    \"name\": \"Bob\         


        
8条回答
  •  醉话见心
    2020-12-01 06:14

    I used Suran's version, but updated it to return non-optional value for decode(). To me this is the most elegant version. Swift 5.2.

    extension KeyedDecodingContainer {
    
    func decodeIfPresent(_ type: Float.Type, forKey key: K, transformFrom: String.Type) throws -> Float? {
        guard let value = try decodeIfPresent(transformFrom, forKey: key) else {
            return nil
        }
        return Float(value)
    }
    
    func decode(_ type: Float.Type, forKey key: K, transformFrom: String.Type) throws -> Float {
        guard let str = try? decode(transformFrom, forKey: key),
            let value = Float(str) else {
                throw DecodingError.typeMismatch(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Decoding of \(type) from \(transformFrom) failed"))
        }
        return value
    }
    }
    

提交回复
热议问题