生成巨大随机数时出现 malloc 错误

malloc error when generating huge random number

我想得到一个从 0 到一个大数 (2^31) 的随机元素。

我尝试从这样的 Range 创建一个 Array(这样我就可以使用 Swift 的 Array.randomElement),就像 所做的那样:

let myArray: [Int64] = [Int64](0...4294967292)

哪个编译,但崩溃:

MyPoject(1569,0x100cc2f40) malloc: can't allocate region mach_vm_map(size=34359738368) failed (error code=3) MyProject(1569,0x100cc2f40) malloc: set a breakpoint in malloc_error_break to debug

当然,我可以写一个 来创建数组,但是那有点味道,尤其是因为数组每次都完全相同。

Swift是否提供了更好的解决方案?

错误信息

malloc: can't allocate region mach_vm_map(size=34359738368)

表示运行时无法分配 32GB 内存——这就是 4294967292 64 位整数数组在

所需要的内存
let myArray: [Int64] = [Int64](0...4294967292)

但是没有必要为此创建数组。从 Swift 4.2 开始,您可以简单地调用

let rnd = Int64.random(in: 0...4294967292)
// or
let rnd = Int64.random(in: 0..<4294967293)

使用其中之一

static func random(in range: ClosedRange<Self>) -> Self
static func random(in range: Range<Self>) -> Self

FixedWidthInteger 协议的方法。

最后注意 4294967292 不是 2^31 = 2147483648 – 如果打算创建一个范围从 0(含)到 2^31(不含)的随机数) 然后

let rnd = Int32.random(in: 0...Int32.max)

会成功的。

ClosedRange 在 Swift 4.2 中也有一个 randomElement 方法:

print((0...4294967292).randomElement()!)

请注意,您说您想要一个介于 0 和 2^31 之间的随机数,但您在示例中使用了 1...4294967292 而不是 0...4294967292