Generating Random Numbers in Swift
Published: 2023-01-10 15:37:51

There are many times when you need to generate random values in your iOS apps such as:

- Simulating dice rolls.
- Shuffling playing cards.
- Creating unique ID for a user.
- Random object from an array.

In Swift 4.2, there are new, simple and secure ways to generate random values. Before that, there was a random function written in C language. Today, you'll learn about the random() function that takes a range of values and as an output it returns a randomly picked value every time.

Let's see how to use random() in Swift to generate random numbers for different primitive data types like Int, Float, Bool etc.

#Generating random number:

All the numeric data types support generation of random number within specified range. You can specify the range values (lower and upper) according to your requirement. Let's take a look at some examples:

```
let randomInt = Int.random(in: 1...99) // 1
// print random value from 1 to 99

let randomInt = Int.random(in: 1..<10) // 2
// print random value from 1 and below to 10

let randomFloat = Float.random(in: 0...1) // 3
// print random float value from 0 to 1. Eg: 0.5673451

let randomBool = Bool.random() // 4
// print true or false randomly
```

Let's understand the above code:

1. Here we are generating a random number Int by passing a range from 1 to 99. So it will always return a number following the same range.

2. Here, it will return a random number Int from given range i.e. 1 to below 10.

3. Here, it will return a random Float value between given range i.e. 0 to 1.

4. Here, it will return a random Bool value that can be either true or false only.

#Generating random value from Collections:

Yes, we can perform randomElement() method to get random object from collections. Many times you need to return random objects from your collection. In Swift, this task is very easy.

##Picking random element from Array:

Let's see how to return random object from an array.

```
let names = ["Amit", "Mayank", "Nitin", "Kanishka", "Shubham"]
let randomName = names.randomElement()
// print any random name like Optional(<name>)
```

> Note: Here, the randomElement() will return an optional object from array so it's a good practice to unwrap the return value using if-let or guard statement like below, since it can return a nil value sometimes.

To pick random object safely, we can use the if-let (optional binding) or guard statement like below:

```
if let randomName = names.randomElement() {
    print(randomName)
} else {
	//handle the nil case here
}
```

In the above code we used if let block, random object will be return safely without any failure and in case of an empty array, it will return nil and the code can be handled gracefully without any crashes.

> When you are picking random object from collection for which you are not sure that it can be empty or nil (or not), good practice is to pick random object with such safe approaches.

##Picking random element from Dictionary:

It's very easy to pick random element from Dictionary. In this case, randomElement() function will return a tuple (grouped of key and value) as result. Let's see how to pick.

```
let userInfo: [String: Any] = ["name": "Amit Samant",
                               "age": 28,
                               "city": "Bangalore",
                               "designation": "iOS Engineer"]
                               
if let randomInfo = userInfo.randomElement() {
    print(randomInfo)
} else {
	//handle the nil case here
}

// random output: (key: "designation", value: "iOS Engineer")
```

In the above code:

1. It will return a random element safely as we are using optional binding here.

2. You can access the values from returned element with the help of dot (.) operator like randomInfo.key and randomInfo.value here.

3. For invalid case like empty dictionary or nil, if condition will not execute and handling will be done in the else block.

#Generating N-digit random number:

To generate a N digit random number, specify the range with the smallest and largest N digit number.

For example, you have to generate a 4-digit pincode in your app, specify the range 1000...9999 to the random() function like below:

```
let randomNumber = Int.random(in: 1000...9999)

// print a 4 digit random number
```
#Working with shuffle() & shuffled():

In Swift, randomising the order of an array is very simple. Swift 4.2 added two new methods shuffle() and shuffled() to shuffle the array elements.

##shuffle():

```
var names = ["Amit", "Mayank", "Nitin", "Kanishka", "Shubham"]  
names.shuffle()

// print elements in random order 
```

shuffle() function shuffles the array in-place, mutating the original array. That's why names variable should be a var not let.

##shuffled():

```
let shuffledNames = names.shuffled()
print(shuffledNames)

// print elements in random order
```

shuffled() function returns a copy of the shuffled array. In this case, original names array will not be change.

> This random() method in Swift 4.2 and higher versions make it easier for developers to generate random values securely and efficiently. As a result, we can write safer and more reliable code.

> Before Swift 4.2, developers used to use arc4random_uniform(n) function to get random value. This function is based on C language style.

Congratulations, It's time to celebrate! Finally you learned about the Random number generator function in Swift and the best practices to use them in your codebase. We recommended you to read more articles like [Functions in Swift](https://www.swiftanytime.com/functions-in-swift/), [Conditional Statements in Swift](https://www.swiftanytime.com/if-else-switch-case-in-swift/) and [What is inout Parameter in Swift](https://www.swiftanytime.com/inout-parameter-in-swift/) till then.

Eat. Sleep. Swift Anytime. Repeat.