Skip to content# Generating a Random Boolean in Swift

— Swift, Random, Boolean — 1 min read

In Swift, there are a few different ways to generate a random Boolean value. Here are three options:

- Using the
`Bool.random()`

method:

This method is part of the Swift standard library and returns a random Boolean value with equal probability of being `true`

or `false`

. To use it, simply call `Bool.random()`

, like this:

`1let randomBool = Bool.random()`

- Using the
`arc4random_uniform(_:)`

function:

This function is part of the `Darwin`

module, which provides access to many low-level functions and data types in the macOS and iOS operating systems. It generates a random unsigned integer value between `0`

and a given upper bound.

To use this function to generate a random Boolean value, you can call `arc4random_uniform(2)`

and check whether the result is `0`

or `1`

. If the result is `0`

, the Boolean value is `false`

, and if the result is `1`

, the Boolean value is `true`

. Here's an example of how to use this function:

```
1import Darwin2
3let randomInt = arc4random_uniform(2)4let randomBool = randomInt == 1
```

- Using the
`Int.random(in:)`

method:

This method is part of the Swift standard library and returns a random integer value within a given range. To use it to generate a random Boolean value, you can call `Int.random(in: 0..<2)`

and check whether the result is `0`

or `1`

. If the result is `0`

, the Boolean value is `false`

, and if the result is `1`

, the Boolean value is `true`

. Here's an example of how to use this method:

`1let randomInt = Int.random(in: 0..<2)2let randomBool = randomInt == 1`

These are just a few options for generating a random Boolean value in Swift. Which one you choose will depend on your specific needs and preferences. Regardless of which method you choose, generating a random Boolean value in Swift is a quick and easy task.