Data.withUnsafeBytes 的替换,因为它在 Swift 5.6 中已弃用

Replacement for Data.withUnsafeBytes because it is deprecated in Swift 5.6

我有一个生成挑战字符串的代码。

    private func codeChallenge(for verifier: String) -> String {
       guard let data = verifier.data(using: .utf8) else { fatalError() }
       var buffer = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
       data.withUnsafeBytes {
          _ = CC_SHA256([=12=], CC_LONG(data.count), &buffer)
       }
       let hash = Data(buffer)
       return hash.base64EncodedString()
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "=", with: "")
        .trimmingCharacters(in: .whitespaces)
    }

它按预期工作,但会生成警告:

'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead

我不确定我是不是疯了,但警告再次引用已弃用的方法作为解决方案。我错过了什么吗?

Am I missing something?

是的。被弃用的是

func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

替换为

func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType

这两个方法中可能都有“withUnsafeBytes”这个短语,但这基本上是无关紧要的;它们是完全不同的方法,具有完全不同的签名。