當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift SystemRandomNumberGenerator用法及代碼示例

結構

SystemRandomNumberGenerator

係統的默認隨機數據源。

聲明

@frozen struct SystemRandomNumberGenerator

概述

當您生成隨機值、打亂集合或執行其他依賴於隨機數據的操作時,此類型是默認使用的生成器。例如,本例中的兩個方法調用是等價的:


let x = Int.random(in: 1...100)
var g = SystemRandomNumberGenerator()
let y = Int.random(in: 1...100, using: &g)

SystemRandomNumberGenerator 是自動播種的,可以在多個線程中安全使用,並盡可能使用加密安全算法。

`SystemRandomNumberGenerator` 的平台實現

雖然係統生成器在每個平台上都是自動播種和線程安全的,但生成器生成的隨機數據流的加密質量可能會有所不同。有關更多詳細信息,請參閱每個平台使用的 API 的文檔。

  • Apple 平台使用 arc4random_buf(3)

  • Linux 平台在可用時使用getrandom(2);否則,他們從 /dev/urandom 讀取。

  • Windows 使用 BCryptGenRandom

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 SystemRandomNumberGenerator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。