To generate a random string in Swift, you can use the random
function along with an array of characters that you want to use. Here is an example:
main.swift434 chars11 lines
In this example, the generateRandomString
function takes a parameter length
, which specifies the length of the random string to generate. The function first defines an array of characters that includes lowercase letters, uppercase letters, and digits.
The function then creates an empty string randomString
and loops length
number of times. In each iteration, the function generates a random index within the bounds of the characters
array, uses that index to get a random character from the array, and appends that character to randomString
.
Finally, the function returns randomString
, which is a random string of the specified length consisting of only the allowed characters.
gistlibby LogSnag