How does one generate a random number in Apple'

2018-12-31 13:07发布

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?

标签: swift random
25条回答
深知你不懂我心
2楼-- · 2018-12-31 13:34

Swift 4.2, Xcode 10.1.

For iOS, macOS and tvOS you can use system-wide random source in Xcode's framework GameKit. Here you can find GKRandomSource class with its sharedRandom() class method:

import GameKit

let number: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func randomGenerator() -> Int {
    let random = GKRandomSource.sharedRandom().nextInt(upperBound: number.count)
    return number[random]
}
randomGenerator()

Or just use a randomElement() method that returns a random element of the collection:

let number: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let randomNumber = number.randomElement()!
print(randomNumber)
查看更多
登录 后发表回答