#### Get 5 of my best practices

##### Learn how to build better iOS apps

I’ll show you exactly how I built a dozen professional iOS apps,

write extensible Swift code, and turn coffee into code.*Wait, what?* Yup – into Swift code.

This article has been updated for Swift 4.

Let’s take a look at randomness and random numbers in Swift. Swift has a number of built in functions that help you generate random numbers, with a few caveats though!

But first… why would you need random numbers in Swift?

- In game development, you need random numbers to simulate dice rolls, or even simulate “chaos” and unpredictability in your games, like random enemy positions or random upgrade spawns
- In indie app development, you need randomness to pick a random number from an array
- When creating an object, or a new user, you sometimes need a random unique ID

Let’s get started!

- Random Number Functions In Swift
- Random Integers with arc4random_uniform(_:)
- Random Doubles with drand48()
- An Easy Function for Random Numbers
- Picking a Random Element from an Array
- Generating A Random String
- Further Reading

Swift has three typical functions for random numbers:

`arc4random()`

returns a random number between zero and 2^{32}–1`arc4random_uniform(_:)`

returns a random number between zero and the first parameter, minus one.`drand48()`

returns a random`Double`

between`0.0`

and`1.0`

Both `arc4random()`

and `arc4random_uniform(_:)`

use the `UInt32`

type instead of the more typical `Int`

.

It’s recommended to use the `arc4random_uniform(_:)`

instead of `arc4random()`

, because the latter suffers from a condition called “modulo bias”. This causes particular numbers to appear more often than others, undermining the “randomness” of the function.

Keep in mind that the random numbers from these functions are *semi-random* and they’re generated with a mathematical function. Although they appear random, if you repeat the random function often enough you’ll see patterns and repetitions. This is fine for games or shuffling an array, but you shouldn’t use these random functions for cryptography or security purposes.

Fun fact: early computers, and especially computer games, included a file with random numbers. The program would sequentially pick random numbers from this file whenever it needed a random number, instead of calculating a random number on its own!

These days the mechanism isn’t much different, although iOS or Android has a large reserve of randomly generated numbers. Calculating a large set of random numbers before using it is known as *seeding*.

I’ll show you exactly how I built a dozen professional iOS apps,

write extensible Swift code, and turn coffee into code.*Wait, what?* Yup – into Swift code.

The function `arc4random_uniform(_:)`

takes one parameter, the *upper bound*. It’ll return a random number between 0 and this upper bound, minus 1.

Like this:

```
arc4random_uniform(42)
// Output: 13
```

This will return a random number between 0 and 41. The result is of type `UInt32`

, so if you want to work with an ordinary integer in your code, you’ll have to convert it to `Int`

.

Like this:

```
let n = Int(arc4random_uniform(42))
```

Constant `n`

is now of type `Int`

, which is much easier to work with.

What about double’s? As you know, a double is a decimal-point number with *double precision*. It’s most often used in Swift for number’s that have commas , or fractions.

This is how you generate a random double in Swift, between `0.0`

and `1.0`

:

```
let d = drand48()
print(d)
// Output: 0.396464773760275
```

Easy!

Quick note: all computers have trouble representing floating-point numbers and fractions, so logically, the `drand48()`

function works by simply putting a couple of *integer* numbers after each other… Neat!

**Build better iOS apps** by mastering best practices and app architecture **» Find out how**

Now, that `arc4random_uniform(_:)`

function is a bit odd to work with. Let’s write a convenience function to help you work with random numbers.

Like this:

```
func random(_ n:Int) -> Int
{
return Int(arc4random_uniform(UInt32(n)))
}
```

This function takes an unnamed parameter `n`

of type `Int`

, and returns an integer number between 0 and `n-1`

. As you can see, inside the `arc4random_uniform(_:)`

call, `n`

is converted to `UInt32`

, and the return value of `arc4random_uniform(_:)`

is converted back to `Int`

.

You can generate a few random numbers, then, like this:

```
for i in 0...100 {
print(random(100))
}
```

This will output a 100 random numbers between 0 and 99.

Swift has a half-open range operator, like this `0..<42`

. Why don’t you use it to change the convenience function?

Like this:

```
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.

Inside the function the result is first added to the lower bound of the range, ensuring that the random number always starts at that lower bound. Inside the `arc4random_uniform(_:)`

function, the lower bound is subtracted from the upper bound so that the returned result lies neatly between the lower and the upper bound.

This function deliberately uses the half-open range generic type `Range`

, instead of the closed range generic `ClosedRange`

, because it better reflects the range of the resulting numbers from `arc4random_uniform(_:)`

.

You can use the random-number-from-range function like this:

```
for i in 0...100 {
print(random(1..<42))
}
```

This will print out a 100 random numbers between 1 and 41.

So, how do you get a random number from an array? Easy!

As you know the function `arc4random_uniform(_:)`

returns an integer between zero and the upper bound. If we use `array.count`

as the upper bound, the function will return an index number within the bounds of the array!

Like this:

```
let names = ["Arthur", "Ford", "Zaphod", "Marvin", "Trillian"]
let random = names[Int(arc4random_uniform(UInt32(names.count)))]
print(random)
// Output: Marvin
```

In this example, a random number between zero and `names.count`

is created, and that’s used to get a value out of the `names`

array with subscript syntax.

You can conveniently turn the example above in an array extension, like this:

```
extension Array
{
func random() -> Element
{
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
}
```

In the same fashion as before, a random element from the array is returned. In the example above, `Element`

refers to a type alias of the element in the array, and `self`

refers to the current array instance.

You can use it like this:

```
let names = ["Arthur", "Ford", "Zaphod", "Marvin", "Trillian"]
print(names.random())
// Output: Trillian
```

Want to shuffle an array? Check out this excellent answer on StackOverflow.

What if you want to generate a random string? You can do that like this:

```
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
}
```

In the above example you define a function `random(_:)`

that takes one unnamed parameter `n`

of type `Int`

. The function then defines an alphabet – the characters it’s going to choose from randomly. In the for-loop, a random character from the string is selected and then appended to variable `s`

. This variable is then returned at the end of the function.

You use it like this:

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

A few things to keep in mind:

- Strings in Swift 4 can be a bit tricky… You can read more about them, here: https://oleb.net/blog/2017/11/swift-4-strings/
- Don’t use these functions to generate random passwords – they aren’t strong enough. Use this, instead: https://random.org/passwords
- Be careful when generating random IDs or keys for your database, because it’s easy to create a collision. It’s often better to use the database framework functions, if there are any.

So, now you know… Got a question? Let me know in the comments!

- How to generate a random number in Swift
- How to pick a random element from an array
- How to generate a random string

Want to learn more? Check out these resources:

**Hi, I'm Reinder.**

I help developers play with code.

- How To Make An App (In 9 Steps)
- How To: Random Numbers in Swift 4
- How To: Pass Data Between View Controllers In Swift (Extended)
- How To: Displaying Alerts With UIAlertController In Swift
- Creating A Simple iOS Game With Swift In Xcode
- How To: Build A Real-Time Chat App With Firebase And Swift

**Got a comment or question? Let me know!** I read and respond to every one. Thanks!

- Reinder de Vries
- pavan teja Vydhik
- Reinder de Vries
- pavan teja Vydhik