Alexey Chekanov Alexey Chekanov - 10 months ago 367
Swift Question

Swift generic data conversion function

I'd like to create a generic function to convert stored Data to different data types like:

import UIKit
import AVKit

func represent<T>(_ data: Data) -> T? {

switch T.self {

case is UIImage:
guard let image = UIImage(data: data) else { return nil }
return image
case is AVAudioPlayer:
guard let audio = try? AVAudioPlayer(data: data) else { return nil }
return audio

default:
return nil
}
}


Now I get "Cast from 'T.Type' to unrelated type 'UIImage'/'AVAudioPlayer' always fails". What's wrong here? Thank you.

Answer Source

I would use protocols here, rather than locking yourself into a fixed, non-extensible number of supported types (those you hard-coded in your switch statement):

import UIKit
import AVKit

protocol DataInitializable {
    init?(data: Data) throws
}

extension UIImage: DataInitializable {}
extension AVAudioPlayer: DataInitializable {}

extension Data {
    func decode<T: DataInitializable>() -> T? {
        do {
            return try T(data: self)
        }
        catch {
            return nil
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download