生成随机Int64 + swift 3

时间:2017-05-02 10:24:24

标签: swift swift3

我们在下面的代码中收到警告。任何人都可以建议什么是错的,以及正确的方法是什么?

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)
}

早些时候它现在很好,它正在发出警告:

  从'UnsafeMutablePointer'到'UnsafeMutablePointer'的'unsafeBitCast'会改变指针类型,并可能导致未定义的行为;在'UnsafeMutablePointer'上使用'withMemoryRebound'方法来重新绑定内存类型

2 个答案:

答案 0 :(得分:2)

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)
}

答案 1 :(得分:0)

为什么不这样呢?

import Foundation

func randomInt64()->Int64 {
    var t = Int64()
    arc4random_buf(&t, MemoryLayout<Int64>.size)
    return t
}

let i = randomInt64()

或更好的泛型

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()