Hello, I'm trying to do something that I think should be simple but I can't figure it out.
Basically I'm trying to make my class respond to a String input and assume a certain associated type for all future operations. I could do this with subclasses and a factory pattern but that seems clunky given Swift's more modern features.
I have tried a few different iterations of giving the Datafile a generic parameter as in class Datafile<DataType: FixedWidthInteger> {}
or similar (class Datafile<DataType> where DataType: FixedWidthInteger
) but I keep getting stuck with that too.
Does anyone have an idea whether this is possible? Here's the essential code I'm working with:
class Datafile {
fileprivate let CurrentDataType: DataType.Type
let activePoints: [Bool]
init?(filepath: String) {
if let CurrentDataType = DataType(from: filepath) {
self.CurrentDataType = CurrentDataType
} else {
return nil
}
}
// ...
getDataPoints() -> [Int16] {
let pointSize = MemoryLayout<CurrentDataType>.size // Swift doesn't agree this is a Type
// ...
var tempBufferArray = [CurrentDataType](repeating: 0, count: 128) // not possible
fread(&tempBufferArray, size, numberOfDataPoints, inputFile)
}
}
The closest I've got is defining a protocol
protocol DataReader {
associatedtype DataType where DataType: FixedWidthInteger
}
and making Datafile
conform to it. But then I'm stuck defining multiple types again, each with their own DataType typealias.