简体   繁体   中英

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

I have a code that is generating challenge string.

    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($0, CC_LONG(data.count), &buffer)
       }
       let hash = Data(buffer)
       return hash.base64EncodedString()
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "=", with: "")
        .trimmingCharacters(in: .whitespaces)
    }

It works as expected, however it generates warning:

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

I am not sure if I am crazy but warning is again referencing deprecated method as a solution. Am I missing something?

Am I missing something?

Yes. The one that is deprecated is

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

The replacement is

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

Those two methods may both have the phrase "withUnsafeBytes" in them, but that is basically irrelevant; they are completely different methods with completely different signatures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM