swift Swift中的随机数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中的随机数相关的知识,希望对你有一定的参考价值。

/// Generating A Random String
func random(_ n: Int) -> String  
{
    let a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

    var s = ""

    for _ in 0..<n  
    {
        let r = Int(arc4random_uniform(UInt32(a.characters.count)))

        s += String(a[a.index(a.startIndex, offsetBy: r)])  
    }

    return s  
}

print(random(8))  
// Output: 6FvUpkzp

/// Picking a Random Element from an Array

let names = ["Arthur", "Ford", "Zaphod", "Marvin", "Trillian"]

let random = names[Int(arc4random_uniform(UInt32(names.count)))]  
print(random)  
// Output: Marvin

extension Array  
{
    func random() -> Element  
    {
        return self[Int(arc4random_uniform(UInt32(self.count)))]  
    }
}
/// A Convenience Function for Random Numbers
func random(_ n:Int) -> Int  
{
    return Int(arc4random_uniform(UInt32(n)))  
}
// This will output a 100 random numbers between 0 and 99.

func random(_ range:Range<Int>) -> Int  
{
    return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))  
}
// Instead of a single input number, this function takes in a Range like 0..<42 and returns a number between 0 and 42, not including 42.

以上是关于swift Swift中的随机数的主要内容,如果未能解决你的问题,请参考以下文章

Swift 5 / Swift UI 中的随机 URL

Swift 2.2 中的循环随机动画方法

Swift UI:使用数组中的随机元素更新视图

如何在 Swift 中生成随机数?

如何在 Xcode11 中的 Swift 中随机播放数组中的音频文件?

Swift - Cloud Firestore 中的唯一 ID