Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating random Int64 + swift 3

Tags:

swift

swift3

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

like image 428
user1828845 Avatar asked Apr 16 '26 23:04

user1828845


1 Answers

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)
}
like image 93
Oskar Avatar answered Apr 19 '26 16:04

Oskar