Swift random number: Its advantages and how to generate it

Swift is a programming language for iOS platforms. This kind of programming language was released in 2014. By using it, users can use lots of great features for their app development. Furthermore, in app development, we frequently need to create random numbers to offer the user a sense of randomness. On the other hand, Swift 4.2 provided a new random API that is native to Swift. So the ArrowHiTech team will talk about random number Swift: Its advantages and how to generate it in this article. Let’s explore. 

Why would you need the random number Swift?

  • Swift random number is used in gaming apps to imitate dice rolls or even “chaos” and unpredictability in games, such as upgrade spawns, random enemy positions 
  • Randomness used in iOS programming to select a random item from an array.
  • You may need a random unique ID when creating an object or a new user.

Swift random number between 4.2 and up?

The way you work with random number Swift has changed in Swift 4.2 and higher. You can now utilize Swift’s native functions instead of the imported C method arc4random(). Let’s take a look at the following example:

Swift random number

In the above example, a swift random number between 0 and 10 is generated. The half-open range operator…< is utilized. Because it provides a range of 0 to 10, excluding 10.

Moreover, you may also acquire a random integer from 0 to 10, including 10, by using the closed range operator… As the following example:

Swift random number

The random(in:) function can be used to generate random number swift values for a variety of primitive types, including Int, Double, Float, and even Bool. As an example:

Swift random number

The above example provides a random number Swift floating-point value between 0 and 1. For example: a number with a fraction.

And the next example produces either true or false – a random boolean! They’re fantastic for testing conditional logic at random.

How about selecting an element at random from an array? This is how you can accomplish it:

Swift random number

You use randomElement() on the names array in the above code. This function can be used on any Collection, including arrays and dictionaries. It’s important to remember that the returned random element is a choice.

Is it possible to shuffle an array using the new random number swift functions in Swift 4.2? Yes! It’s surprisingly easy to change the order of an array:

Swift random number

Because of using Swift’s standard naming structure. So Shuffle() shuffles the array in-place, altering the original array, and shuffled() provides a copy of the shuffled array. 

You can also shuffle a Sequence, as shown here:

Swift random number

Random number Swift Functions Before Swift 4.2

For random number Swift, Swift has three functions:

  • arc4random() generates an integer between 0 and 232–1 at random.
  • arc4random uniform(_:) gives a random number between zero and the first parameter, minus one..
  • drand48() generates a Double value between 0.0 and 1.0 at random.

Instead of the more common Int, arc4random() and arc4random uniform(_:) use the UInt32 type.

Because arc4random() suffers from a phenomenon known as “modulo bias,” it suggested that you use arc4random uniform(_:). This makes certain numbers appear more frequently than others, weakening the function’s “randomness.”

Remember that the random integers created by these methods are semi-random and generated using a mathematical function. Although they appear to be random, if you use the random function frequently enough, patterns and repeats will occur. This is acceptable for games or shuffling an array, but these random functions should not be used for cryptography or security.

Although iOS or Android has a big reserve of randomly generated integers, the technique isn’t much different these days. Seeding is the process of calculating a large number of random numbers before using them.

Random number Swift with “arc4random_uniform(_:)”

The upper bound is the only parameter of the function arc4random uniform(_:). It’ll give you a number between 0 and this upper bound, minus one.

For example:

Swift random number

This will generate a number between 0 and 41 at random. Because the result is of type UInt32, you’ll need to convert or type cast it to Int if you wish to use it in your code.

As an example:

Swift random number

Constant n renamed to Int, making it easier to work with.

Random Doubles with “drand48()”

How about doubles? A double is a decimal-point number with double precision, as you may know. It’s most commonly used in Swift for comma-separated numbers or fractions.

In Swift, here’s how to make a random double between 0.0 and 1.0:

Swift random number

NOTE: Because all computers struggle to represent floating-point values and fractions. Therefore, the drand48() function logically works by simply adding two integer numbers after each other.

An Easy Function for random number Swift

Because that arc4random uniform(_:) function is a little strange to use. Let’s develop a function to make working with random integers easier.

For example:

iOS app development

This function accepts an unnamed Int parameter n and returns an integer between 0 and n-1. n transformed to UInt32 inside the arc4random uniform(_:) function, and the return value of arc4random uniform(_:) converted back to Int.

NOTE: You won’t need these convenience functions if you’re using Swift 4.2 or higher. Use .random() or .randomElement(), as described in the previous chapters.

After that, make a few random integers like this:

iOS programming language

This will generate 100 random numbers ranging from 0 to 99.

A half-open range operator, such as 0..42, is available in Swift. Why don’t you try changing the convenience function with it?

For example:

Swift random number

Instead of a single number, this function accepts a Range, such as 0…<42, and returns a number between 0 and 42, excluding 42.

The outcome of the function is initially added to the range’s lower bound. So it ensures that the random number swift always begins at that lower bound. Additionally, the lower bound is subtracted from the upper bound inside the arc4random uniform(_:) function. As a result, it falls nicely within the lower and upper bounds.

Because the range of the returning integers from arc4random uniform(_:) is better reflected by the half-open range generic type Range rather than the closed range generic type ClosedRange, this function utilizes the half-open range generic type Range instead of the closed range generic type ClosedRange.

The random-number-from-range function can be used in the following way:


This will generate 100 random numbers ranging from 1 to 41.

Picking a Random Element from an Array

What is the best way to generate a random number from an array?

The function arc4random uniform(_:) returns an integer between 0 and the upper bound, as you may know. The function will return an index number within the bounds of the array if we use array.count as the upper bound!

For example:


In this example, a random number between zero and names.count generated and used with subscript syntax to extract a value from the names array.

You may easily convert the previous example into an Array extension, á the following example:

random number

A random element from the array returned in the same way as before. In the previous example, Element is a type alias for the array’s element, and self is the current array instance.

You can put it to use in the following way:

Generating a Random String – random number swift

What if you’d like to make a random string? This is how you can do it:

func randomString(_ n: Int) -> String 


    let digits = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”

    var result = “”

    for _ in 0..<n {

        result += String(digits.randomElement()!)


    return result


func randomString(_ n: Int) -> String {

In the previous example, you define the function random(_:), which takes one unnamed Int parameter n. The function then defines an alphabet, or a set of letters from which it will choose at random. The for-loop selects a random character from the string and appends it to the variable result.

A more short summary of the randomString(_:) function is shown below. It works by converting a range of integers into random digit characters, which are then transformed back to a String.

    let digits = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”

    return String(Array(0..<n).map { _ in digits.randomElement()! })


This is how you use the function:

let password = randomString(24)


// Output: qGUjakGkjlRb1sd5jDaj2raW


  • Strings in Swift might be difficult…
  • These functions should not be used to generate random passwords since they are not secure. Instead, use a password organizer like 1Password.
  • When creating random IDs or keys for your database, be careful because it’s easy to make a mistake. It’s better to utilize a string generator that generates unique strings, such as UUID.


Hopefully, the above information about random number Swift is helpful for you, If it is not enough for you to develop app development. Don’t worry about that. Please visit us at our iOS app development services to get more information. We will help you succeed.