swift - 生成随机 Int64 + swift 3

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

之前没问题,现在提示警告:

'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/

相关文章:

ios - mapKit 不显示注释

ios - 带有阿拉伯语文本输入的动态 TextView

ios - Swift applicationDidBecomeActive 观察者 UIApplicationDidBecomeActive 没有被调用

ios - 如何在 Swift 3 中设置每天特定时间的闹钟?

swift - 已安装 cocoapods 但无法导入

swift - 当我取消选择 UICollectionView 中的项目时应用程序崩溃

objective-c - XC测试 |词法或预处理器问题 : MyProject-Swift. h 未找到

ios - 需要在 AppDelegate 导航栏左侧设置 logo

xcode - 使用物理静音 iPhone 按钮使 AVFoundation 声音静音

ios - 数组 Swift 中的唯一对象