Swift 隨機數生成

// 隨機數生成

// arc4random 隨機數算法

let dicFaceCount = 6

let randomRoll = Int(arc4random()) % dicFaceCount + 1

print(randomRoll)

// 這是因為, arc4random所返回的不論在什么平臺都是一個 UInt32, 無符號整形,相當于一個 Int64 的 >=0 的部分

// 而 Int()? 在 32位機上裝不下 UInt32, 所以在32位機上有時會崩潰

// 這個函數是上一個的改良版本

// arc4random_uniform(<#T##__upper_bound: UInt32##UInt32#>)

// 內部實現是,將 n 作為輸入, 將結果歸化到 0 到 n-1 之間,只要我們的輸入不超過 Int 的方位,就可以避免危險的轉換

let dicFaceCount1: UInt32 = 6

let randomRoll1 = Int(arc4random_uniform(dicFaceCount1)) + 1

print(randomRoll1)

let range = Range(uncheckedBounds: (0, 5))

let start = range.lowerBound

let end = range.upperBound

// 在一個 Range中 隨機返回一個 值

func random(in range: Range) -> Int{? ?

?let count = UInt32(range.upperBound - range.lowerBound)? ?

?return Int(arc4random_uniform(count)) + range.lowerBound}

for _ in 0..<10 {? ??

let range = Range(1...6)

print(random(in: range))

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容