无法将类型 'UnsafePointer<T>' 的值转换为预期的参数类型 'UnsafePointer<Int16>'

Cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafePointer<Int16>'

我正在尝试手动将 Swift 3 代码转换为 Swift 5,但是在尝试转换内存时出现错误。

   let buffer: UnsafePointer<Int16>

   init<T>(buffer: UnsafePointer<T>) {
      self.buffer  = UnsafePointer<Int16>(buffer)
   }

错误是新 Swift 版本不允许的强制类型转换。

   Cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafePointer<Int16>'

我不确定将内存重新绑定到“UnsafePointer<Int16>”的正确方法是什么,强制

The UnsafePointer reference page 解释了正确但乏味的过程:

When you need to permanently rebind memory to a different type, first obtain a raw pointer to the memory and then call the bindMemory(to:capacity:) method on the raw pointer. The following example binds the memory referenced by uint8Pointer to one instance of the UInt64 type:

let uint64Pointer = UnsafeRawPointer(uint8Pointer)
                          .bindMemory(to: UInt64.self, capacity: 1)

你应该告诉编译器你重新绑定了多少内存(使用 capacity 参数)因为它可能已经将一些内存复制到寄存器或堆栈并且它需要知道你正在使这些副本无效。