How to get random characters from a string in Swift

Overview

In Swift, the randomElement() method is used to get a random character from a string. However, if the string is empty, the method returns nil.

Syntax

string.randomElement()

Parameters

This method takes no parameters.

Return Value

It returns a random character from the string.

Example

// create string values
let name = "Theodore"
let language = "Swift"
let role = "Software Developer"
// get random characters from
// strings and print results
print(name.randomElement()!)
print(language.randomElement()!)
print(role.randomElement()!);

Explanation

  • Lines 2–4: We create the string’s name, language, and role.
  • Lines 8–10: We use the randomElement() method to get random characters from the strings. Next, we print the values to the console.

Free Resources