ValidKeyedCodingValueProvider

public protocol ValidKeyedCodingValueProvider

A protocol that your Codable type can adopt, in order to supply values for fields that are validated during decoding.

The TypeDecoder operates by constructing a ‘dummy’ instance of a type, via the init(from: Decoder) initializer. As there is no real data to be decoded, dummy values (such as 0 and "") are provided. This may cause an initializer that requires specific valid values to fail.

To enable such a type to work with TypeDecoder, define an extension that conforms the type to the ValidKeyedCodingValueProvider protocol. The validCodingValue(forKey:) function should return a valid value for fields that requires validation.

Usage Example:

public class YoungAdult: Codable {
    let name: String
    let age: Int
    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: CodingKeys.name)
        self.age = try container.decode(Int.self, forKey: CodingKeys.age)
        // Validate the age field
        guard self.age >= 18, self.age <= 30 else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Age is outside the permitted range"))
        }
    }
}

// Provide a value for 'age' which is within the acceptable range
extension YoungAdult: ValidKeyedCodingValueProvider {
    public static func validCodingValue(forKey key: CodingKey) -> Any? {
        switch key.stringValue {
        case self.CodingKeys.age.stringValue:
            return 20
        default:
            // For any fields that are not validated, you may return nil.
            // The TypeDecoder will use a standard dummy value.
            return nil
        }
    }
}
  • Returns a value for a CodingKey that represents a field that requires validation. nil may be returned for all other fields.

    Usage Example:

    switch key.stringValue {
    case self.CodingKeys.email.stringValue:
        return "joe@example.com"
    default:
        return nil
    }
    

    Declaration

    Swift

    static func validCodingValue(forKey: CodingKey) -> Any?