generate a random string in swift

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.swift
func generateRandomString(length: Int) -> String {
    let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var randomString = ""
    for _ in 0..<length {
        let randomIndex = Int.random(in: 0..<characters.count)
        let randomCharacter = characters[characters.index(characters.startIndex, offsetBy: randomIndex)]
        randomString.append(randomCharacter)
    }
    return randomString
}
434 chars
11 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