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

Time:03-27

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?

CodePudding user response:

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.

  • Related