首页 > 解决方案 > 如何处理`withUnsafeBytes`被弃用的警告?

问题描述

我收到以下代码的弃用警告,

_ = data.withUnsafeBytes {
    _ = CC_SHA256($0, CC_LONG(data.count), &digest)
}

'withUnsafeBytes' 已弃用:withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R改用

我该如何处理?

更新

正如 Martin 所建议的,我在Swift-5 中使用了以下代码,

func sha256(data : Data) -> Data {
    var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
    data.withUnsafeBytes {
        _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
    }
    return Data(hash)
}

这甚至给编译器错误,

“UnsafePointer<_>”类型的值没有成员“baseAddress”

更新2

Martins 解决方案在 Xcode 11.3.1 中运行良好。但它在 Xcode 11 中不起作用。

标签: swiftdeprecatedsha256

解决方案


Martin的解决方案适用Xcode 11.3.1+

func sha256(data : Data) -> Data {
    var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
    data.withUnsafeBytes {
        _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
    }
    return Data(hash)
}

推荐阅读