我正在对我不太理解的代码进行一些 Swift 5 转换,即以前开发人员的遗留代码。我得到:
'withUnsafeBytes' 已弃用:改用 withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R`
为了:
func toArray<T>(type: T.Type) -> [T] {
return self.withUnsafeBytes {
[T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
}
}
我想用这个替换它,但我不确定它是否做同样的事情:
func toArray<T>(type: T.Type) -> [T] where T: ExpressibleByIntegerLiteral {
var array = [T](repeating: 0, count: self.count/MemoryLayout<T>.stride)
_ = array.withUnsafeMutableBytes { copyBytes(to: $0) }
return array
}
在这两个 fxs 的上下文中使用:
static func extractPacketSizeFromIV(iv: Data) -> Int32? {
let array = iv.toArray(type: Int32.self)
guard array.count == 4 else { return nil }
let r0 = array[0].bigEndian
let r1 = array[1].bigEndian
let r2 = array[2].bigEndian
return r2 ^ r1 ^ r0
}
static func extractGuidFromIV(iv: Data) -> Int32? {
let array = iv.toArray(type: Int32.self)
guard array.count == 4 else { return nil }
let r0 = array[0].bigEndian
let r1 = array[1].bigEndian
let r2 = array[2].bigEndian
let r3 = array[3].bigEndian
return r3 ^ r2 ^ r1 ^ r0
}