How does one generate a random number in Apple's Swift language?

后端 未结 25 2073
有刺的猬
有刺的猬 2020-11-22 09:51

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 t

25条回答
  •  日久生厌
    2020-11-22 10:32

    Updated: August 06, 2020.

    Swift 5.3

    Let's assume we have an array:

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


    For iOS and macOS 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
    
    private func randomNumberGenerator() -> Int {
        let random = GKRandomSource.sharedRandom().nextInt(upperBound: numbers.count)
        return numbers[random]
    }
    
    randomNumberGenerator()
    


    Also you can use a randomElement() method that returns a random element of a collection:

    let randomNumber = numbers.randomElement()!
    print(randomNumber)
    


    Or use arc4random_uniform(). Pay attention that this method returns UInt32.

    let generator = Int(arc4random_uniform(10))
    print(generator)
    


    And, of course, we can use a makeIterator() method that returns an iterator over the elements of the collection.

    let iterator: Int = (1...10).makeIterator().shuffled().first!
    print(iterator)
    


    The final example you see here returns a random value within the specified range with a help of static func random(in range: ClosedRange) -> Int.

    let randomizer = Int.random(in: 1...10)
    print(randomizer)
    

提交回复
热议问题