Swift String randomElement() Method



String randomElement() Method

The randomElement() method is used to find a random character from the given string. So whenever you run the code you will get a different output. For example, we have a string Swift, now we find a random character using randomElement() and we will get w.

Syntax

Following is the syntax of the randomElement() method −

func randomElement()

Parameters

This method does not take any parameters.

Return Value

This method returns a random character. The value return by this method is optional so we have to unwrap the result to get the actual value.

Example 1

Swift program to demonstrate how to use the randomElement() method −

import Foundation

// Declaring a string
var str = "TutorialsPoint"
print("Original string:", str)

// Using randomElement() method
var result = str.randomElement()!
print("Random Character:", result)

Output

Original string: TutorialsPoint
Random Character: i

Example 2

Swift program to get a random character of the given string −

import Foundation

// Declaring a string
var str = "Car"
print("Original string:", str)

// Random character
if let result = str.randomElement(){
   print("Random Character:", result)
}

Output

Original string: Car
Random Character: C
swift_strings.htm
Advertisements