×

Random Number Functions In Swift 4.2+

Falcon 2020-01-08 views:
自动摘要

正在生成中……

In Swift 4.2. and after, the way you work with random numbers has changed. Instead of using the imported C function arc4random(), you can now use Swift’s own native functions.

Let’s look at an example:

let number = Int.random(in: 0 ..< 10)

The above example generates a random integer number between 0 and 10. The half-open range operator ..< is used, and the result is a range that runs from 0 to 10, not including 10.

You can also use the closed range operator ··· to get a random integer from 0 to 10, including 10. Like this:

let number = Int.random(in: 0 ··· 10)

You can use the random(in:) function to get random values for several primitive types, such as IntDoubleFloat and even Bool. Like this:

let fraction = Float.random(in: 0 ..< 1)

The above example returns a random floating-point value, i.e. a number with a fraction, between 0 and 1.

And this example either returns true or false – a random boolean!

let stayOrGo = Bool.random()

What about picking a random element from an array? You can do that like this:

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

let randomName = names.randomElement()

In the above code you use randomElement() on the names array. You can use this function on any Collection, such as arrays and dictionaries. Keep in mind that the returned random element is an optional.

Can you also use the new random functions in Swift 4.2. to shuffle an array? Yes! Randomizing the order of an array is surprisingly simple:

let names = ["Ford", "Zaphod", "Trillian", "Arthur", "Marvin"]
names.shuffle()
// `names` can now be: ["Zaphod", "Marvin", "Arthur", "Ford", "Trillian"]

The shuffle functions use Swift’s typical naming structure, so shuffle() shuffles the array in-place, and shuffled() returns a copy of the shuffled array.

And you can even shuffle a Sequence, like this:

let sequence = 0 ..< 7
let shuffledSequence = sequence.shuffled()
// `shuffledSequence` can now be: [0, 6, 2, 3, 4, 1, 5]

Easy, right? Much easier than the pre-4.2 arc4random_uniform(_:) with all that type casting…