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
.
string.randomElement()
This method takes no parameters.
It returns a random character from the string
.
// 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()!);
name
, language
, and role
.randomElement()
method to get random characters from the strings. Next, we print the values to the console.RELATED TAGS
CONTRIBUTOR
View all Courses