请查看以下游乐场代码:
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)
}
第一个do块按预期执行。第二个块表示我的问题。第二个块的基本思想是:我不知道数据的类型;其他东西会告诉我。我想做什么?也许getType函数和/或Data扩展方法的签名需要不同?