1

我将一个项目更新为 Swift 5,它使用以下代码在某处生成用于加密的密钥:

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

随着对 Swift 5 的更新,我收到以下警告:

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

但是我不知道如何实现它想要的东西,我发现这个建议充其量是模糊的,而且我尝试的任何东西要么无法编译,要么给出相同的警告。

这是完整的功能:

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
}

我尝试了各种写作方式,withUnsafeMutableBytes但都无济于事。Swift 5 中上述代码的合适替代方案是什么?

4

0 回答 0