Swift 4 Codable: Converting JSON return String to Int/Date/Float

后端 未结 2 1494
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 12:15

I\'m going through some projects and removing JSON parsing frameworks, as it seems pretty simple to do with Swift 4. I\'ve encountered this oddball JSON return where I

2条回答
  •  执念已碎
    2020-12-31 12:15

    public extension KeyedDecodingContainer {
    public func decode(_ type: Date.Type, forKey key: Key) throws -> Date {
        let dateString = try self.decode(String.self, forKey: key)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"
        guard let date = dateFormatter.date(from: dateString) else {
            let context = DecodingError.Context(codingPath: codingPath,
                                                debugDescription: "Could not parse json key to a Date")
            throw DecodingError.dataCorrupted(context)
        }
        return date
    }
    }
    

    Usage: -

    let date: Date = try container.decode(Date.self, forKey: . createdDateTime)
    

提交回复
热议问题