ValidSingleCodingValueProvider

public protocol ValidSingleCodingValueProvider

A protocol that your Codable type can adopt, in order to supply a valid value during decoding. This protocol is suitable for types that are represented by a single encoded value, such as an enum.

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, a dummy value (such as 0 or "") is provided. This may cause an initializer that requires a specific valid value to fail.

To enable such a type to work with TypeDecoder, define an extension that conforms the type to the ValidSingleCodingValueProvider protocol. The validCodingValue() function should return a valid encoded representation of that type.

Usage Example:

public enum Fruit: String, Codable {
    case apple, banana, orange, pear
}

// Provide an acceptable value during decoding
extension Fruit: ValidSingleCodingValueProvider {
    public static func validCodingValue() -> Any? {
        // Returns the string "apple"
        return self.apple.rawValue
    }
}
  • Returns a valid encoded representation of the conforming type.

    Usage Example:

        self.apple.rawValue
    

    Declaration

    Swift

    static func validCodingValue() -> Any?