Turning a case let with varying associated value types into a function call
Parsing a TIFF file, I've got a structure like this:
struct
DirectoryEntry
{
enum
Value
{
case signedInt([Int64])
case unsignedInt([UInt64])
case rational([Rational])
case srational([SRational])
case double([Double])
}
let count : UInt64
let values : Value?
}
Each DirectoryEntry (or tag) in a TIFF file can have one or more values of a specified
type, represented by the enumeration above (Rationa1 and SRational are structs
that hold two integers).
When I process the various tags, I have an expansive switch statement:
let de = readDirectoryEntry()
switch (de.tag)
{
...
case .compression:
guard
case let .unsignedInt(values) = de.values,
de.count == 1
else
{
throw Error.invalidTIFFFormat
}
ifd.compression = try CompressionType.compression(fromVal: values.first!)
...
}
I'd like to reduce the boilerplate code to validate the de with something like this:
case .compression:
let values = try de.validate(type: .unsignedInt, count: 1)
ifd.compression = try CompressionType.compression(fromVal: values.first!)
Such that values is of the appropriate associated type, depending on which specific
type it is. In the above example, it would be [UInt64]. Iām not sure how to express
that in Swift, though. Is there a way to specify the type of T based on what type: is?