Generate random alphanumeric string in Swift


In this article, you will learn various ways to generate random alphanumeric strings in the Swift language.

Here we are going to use the following 3 methods to generate a random alphanumeric string in swift −

  • Using the RandomNumberGenerator protocol

  • Using the Random() function

  • Using higher-order functions

Using the RandomNumberGenerator protocol

Swift 5 comes with a random() function that is added to the Foundation framework. We will use the RandomNumberGenerator protocol as the random() function is a part of this protocol.

Example

The following example demonstrates on how to use the random() function to generate a random alphanumeric string in Swift 5 −

import Foundation
func randomAlphanumericString(_ length: Int) -> String {
   let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
   let len = UInt32(letters.count)
   var random = SystemRandomNumberGenerator()
   var randomString = ""
   for _ in 0..<length {
      let randomIndex = Int(random.next(upperBound: len))
      let randomCharacter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
      randomString.append(randomCharacter)
   }
   return randomString
}

// Calling this function to generate a random string of any length, like this:
let randomString = randomAlphanumericString(10)
print("Random alphanumeric string: \(randomString)")

Output

Random alphanumeric string: VXU9XlmO0U

Note − the output will be generated randomly.

This function is using the next(upperBound:) method of the SystemRandomNumberGenerator protocol to generate a random number between 0 and the number of characters in the letters string.

Once the random characters are generated, it appends them to the randomString (output string).

Using the Random() function

This is another way to generate a random alphanumeric string in Swift is to use the String and random() function. Here's an example of how to use it to generate a random string with a specific length −

Example

import Foundation
func randomAlphanumericString(_ length: Int) -> String {
   let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
   var randomString = ""
   for _ in 0..<length {
      let randomIndex = Int.random(in: 0..<letters.count)
      let randomCharacter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
      randomString.append(randomCharacter)
   }
   return randomString
}
// Calling this function to generate a random string of any length, like this:
let randomString = randomAlphanumericString(10)
print("Random alphanumeric string: \(randomString)")

Output

Random alphanumeric string: WTU6XlbO1U

In the random function, the index can be used to select a random character from the letters string and appends it to the randomString.

Using higher-order functions

Another way to generate a random alphanumeric string in Swift 5 is to use the String and randomElement() method, which is available as of Swift 5.1. For below Swift versions, this function will not work. You can find an alternative way for older Swift versions.

Example

import Foundation
func randomAlphanumericString(_ length: Int) -> String {
   let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
   let randomString = (0..<length).map{ _ in String(letters.randomElement()!) }.reduce("", +)
   return randomString
}
// Calling this function to generate a random string of any length, like this:
let randomString = randomAlphanumericString(10)
print("Random alphanumeric string: \(randomString)")

Output

Random alphanumeric string: A5K6XBbP2W

This function generates a range of numbers of the desired length and maps it to a random element of the letters string, then concatenates all of the elements together to form a single string. The randomElement() method selects a random character from the letters string, and the reduce method concatenates all substrings into a single string.

Conclusion

Finally, there are several ways to generate a randomly generated alphanumeric string in Swift. The Foundation framework's random() function is used to generate random numbers that can be used to generate a random alphanumeric string. Swift 5.1+'s random() function and randomElement() method are also viable options for generating random alphanumeric strings. Depending on your needs, any of these Swift methods could be useful for generating a random alphanumeric string.

Updated on: 28-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements