Please have a look at the following playground code:
import Foundation
public extension Data {
public func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.pointee }
}
}
let data = Data(bytes: [1, 0, 0, 0])
do {
let type = Int32.self
print("\(type)'s type is \(type(of: type))") // prints "Int32's type is Int32.Type"
let value = data.to(type: type)
print(value) // prints "1"
}
do {
func getType() -> Any.Type { return Int32.self }
let type = getType()
print("\(type)'s type is \(type(of: type))") // prints "Int32's type is Int32.Type"
let value = data.to(type: type) // error: cannot invoke 'to' with an argument list of type '(type: Any.Type)'
print(value)
}
The first do block executes as expected. The second do block illustrates my issue. The basic idea of the second block is: I do not know the type of the data; something else is going to tell me. Is what I want to do possible? Perhaps the signatures of the getType function and/or the Data extension's to method need to be different?