#StackBounty: #swift #generics Swift 5 dynamic type for array

Bounty: 50

I have the following code in Swift:

class VolumeData <T> {
   private var volume: [T]

   init(with data:Data, width: UInt32, height: UInt32, depth: UInt32) {
      let size = width * height * depth
      volume = data.arrayFromData(size: Int(size))

class Volume: NSObject {

    private var rawVolume : Data?
    public var volume : VolumeData<Any>?
    public var header: Header?


    func loadVolume(_ name: String) {
        let filepath = Bundle.main.path(forResource: name, ofType: "vol")
        rawVolume = try? Data.init(contentsOf: URL(fileURLWithPath: filepath ?? ""))
        header = Header.init(from: ((rawVolume?.subdata(in: 0..<284))!))
        let volSize = header!.width * header!.height * header!.depth
        switch header!.type {
        case .FLOAT:
             volume = VolumeData<Float32>(with: (rawVolume?.subdata
             (in: 284..<volSize))!, width: header!.width, 
             height: header!.height, depth: header!.depth)
            volume = nil

And for the sake of completion:

extension Data {
    func arrayFromData<T> (size: Int) -> [T] {
       var arr:[T] = []
       for i in 0..<size {
           let offset = 4*i
           let d:T = self[offset..<offset+4].withUnsafeBytes { $0.pointee }
        return arr

Right now I have a compile-time error:

Cannot assign value of type 'VolumeData<Float32>' (aka 'VolumeData<Float>') 
  to type 'VolumeData<Any>?'

Anyone can point me the correct way to implement this kind of dynamic generics in Swift?

Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.