Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
characters
string
random
communitycreator

How to get random characters from a string in Swift

Theodore Kelechukwu Onyejiaku

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()!);
Get random characters from a string in Swift

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.

RELATED TAGS

swift
characters
string
random
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring