我们在下面的代码中收到警告。谁能指出哪里出了问题以及正确的方法是什么?
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/