Swift Program to Create random strings


In Swift, a random string is a sequence of characters. It is generated by randomly selecting characters from a set of available characters, for example: “fbbKDvf”, “dvsWFVsvdv”, etc. So to create random strings Swift provides the following methods −

  • Using randomElement() method

  • Using UUID

Method 1: Using randomElement() method

Swift provides an inbuilt function named as randomElement() method. This function returns a random element from the given sequence or collection.

Syntax

func randomElement()

It returns random elements. If the given collection is empty, then it will return nil.

Algorithm

  • Step 1 − Create a function that takes the length of the random string.

  • Step 2 − Inside the function create a variable and store all the alphabets in lower and uppercase to generate a random string.

  • Step 3 − Call randomElement() method on the variable and select characters randomly. Then uses the map() method to repeat the process strLen times, to generate random characters each time.

  • Step 4 − Now use the String() initializer to join the array of characters into a string.

  • Step 5 − Return the final string.

  • Step 6 − Now call the above function and pass the length of the string into it.

  • Step 7 − Print the output.

Example

In the following Swift program, we will create random strings. So for that, we define a function which takes the desired length of the random string. Then it uses randomElement() function to select characters randomly from the given string, then uses the map() function to repeat the process strLen times. Finally, it uses String() initializer to join the array of characters to create a string. And return a randomly created string of the given length.

import Foundation
import Glibc

func buildRandomString(strLen: Int) -> String 
{
   let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
   let resStr = String((0..<strLen).map{_ in chars.randomElement()!})
   return resStr
}

let randomStr = buildRandomString(strLen: 17)
print("Random String:", randomStr)

Output

Random String: yVgCHlrGwcKKdDvID

Method 2: Using UUID Structure

UUID is an inbuilt structure to provide universally unique value to identify types, interfaces, etc. Here we will use uuidString property of UUID structure to get a random string like “EUVVB3-N43U-MV2N-HF2M- BVIV321NVFI6NF”.

Algorithm

  • Step 1 − Create a function that returns a random string.

  • Step 2 − Inside the function create an instance of the UUID structure.

  • Step 3 − Call the uuidString property to get the random string.

  • Step 4 − Return the random string.

  • Step 5 − Now call the above function.

  • Step 6 − Print the output.

Example

In the following Swift program, we will create random strings. So for that, we define a function that returns a random string. This function creates an instance of UUID and returns a random string using uuidString property.

import Foundation
import Glibc

// Function to find the random string 
func createRandomStr() -> String 
{
   let resultStr = UUID()
   return resultStr.uuidString
}

let randomStr = createRandomStr()
print("Random String:", randomStr)

Output

Random String: 54ED454E-44D6-453A-9618-BD28E3F5C9A9

Conclusion

So this is how we can create a random string. Random strings are useful for generating unique identifiers, for creating secure passwords, simulating data, etc. Also while using the randomElement() function use optional wrapping because it returns nil if the collection is empty.

Updated on: 13-Jun-2023

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements