We are getting warnings in the below code. Can anyone suggest what's wrong and what the correct approach would be?
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)
}
Earlier it was fine now it's giving the warning:
'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 introduced withMemoryRebound, replacing unsafeBitCast and other unsafe casts: https://developer.apple.com/reference/swift/unsafepointer/2430863-withmemoryrebound
The correct way to use it in your case:
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With