1

I updated a project to Swift 5, it generates a key for encryption somewhere with the following piece of code:

let result = key.withUnsafeMutableBytes { bytes in
    SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
}

With the update to Swift 5 I get the following warning:

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

But I have no idea how to implement what it wants from me, I find the suggestion vague at best and anything I try either doesn't compile or gives the same warning.

Here is the full function:

static func generateEncryptionKey() -> Data {
    /// Generate a random encryption key
    var key = Data(count: 64)

    let result = key.withUnsafeMutableBytes { bytes in
        SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
    }
    assert(result == 0, "Failed to get random bytes")

    let keyHexString = (key as NSData).hexStringRepresentation()
    debugPrint("Newly generated encryption key - \(keyHexString)")

    return key
}

I've tried various ways of writing withUnsafeMutableBytes but to no avail. What would be a suitable alternative for above code in Swift 5?

  • Have a look at https://stackoverflow.com/a/39820681/1187415, which has been updated for Swift 5. – Martin R Apr 16 '19 at 07:55
  • @MartinR Thanks a lot, that works. I don't know if you want to post an answer I can accept? Else I'll just mark this Q as duplicate. – Kevin Wessels Apr 16 '19 at 08:01

0 Answers0