gpt4 book ai didi

swift - 生成随机 Int64 + swift 3

转载 作者:搜寻专家 更新时间:2023-10-31 22:42:37 25 4
gpt4 key购买 nike

我们在下面的代码中收到警告。谁能指出哪里出了问题以及正确的方法是什么?

class func getRandomInt64() -> Int64 {
var randomNumber: Int64 = 0
withUnsafeMutablePointer(to: &randomNumber, { (randomNumberPointer) -> Void in
let castedPointer = unsafeBitCast(randomNumberPointer, to: UnsafeMutablePointer<UInt8>.self)
_ = SecRandomCopyBytes(kSecRandomDefault, 8, castedPointer)
})
return abs(randomNumber)
}

之前没问题,现在提示警告:

'unsafeBitCast' from 'UnsafeMutablePointer' to 'UnsafeMutablePointer' changes pointee type and may lead to undefined behavior; use the 'withMemoryRebound' method on 'UnsafeMutablePointer' to rebind the type of memory

最佳答案

Swift 3 引入了 withMemoryRebound,取代了 unsafeBitCast 和其他不安全的转换:https://developer.apple.com/reference/swift/unsafepointer/2430863-withmemoryrebound

在您的情况下正确使用它的方法:

class func getRandomInt64() -> Int64 {
var randomNumber: Int64 = 0
withUnsafeMutablePointer(to: &randomNumber, { (randomNumberPointer) -> Void in
_ = randomNumberPointer.withMemoryRebound(to: UInt8.self, capacity: 8, { SecRandomCopyBytes(kSecRandomDefault, 8, $0) })
})
return abs(randomNumber)
}

关于swift - 生成随机 Int64 + swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43735565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com