Generating a random Int64 + swift 3
We are getting warnings in the code below. Can anyone suggest what is wrong and what is the correct approach?
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)
}
It used to be fine, now he warned:
"unsafeBitCast" from "UnsafeMutablePointer" to "UnsafeMutablePointer" changes the target's type and may result in undefined behavior; use the "withMemoryRebound" method in the "UnsafeMutablePointer" to re-restore the memory type
+3
source to share
2 answers
Swift 3 introduced withMemoryRebound
, replacing unsafeBitCast
other unsafe casts as well: 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)
}
+2
source to share
why not?
import Foundation
func randomInt64()->Int64 {
var t = Int64()
arc4random_buf(&t, MemoryLayout<Int64>.size)
return t
}
let i = randomInt64()
or better with a common
import Foundation
func random<T: Integer>()->T {
var t: T = 0
arc4random_buf(&t, MemoryLayout<T>.size)
return t
}
let i:Int = random()
let u: UInt8 = random()
0
source to share