3 Ways to Generate Random Strings in Swift

Updated: February 23, 2023 By: Khue Post a comment

This practical, succinct article walks you through 3 different ways to generate a random string in Swift. Without any delay, let’s get started.

Using UUID

UUID stands for “Universally Unique Identifier” and is a standard way to generate random strings. UUIDs are 36 characters long and include letters, numbers, and hyphens.

Example:

import Foundation

let u1 = UUID().uuidString
let u2 = UUID().uuidString

print("u1: \(u1)")
print("u2: \(u2)")

Output (not consistent):

u1: C43E2BE1-0486-402E-86CE-AEDC0B3DAF8A
u2: 17051068-C0C4-4213-A7D0-E682A0546155

Due to the randomness, you will get different results each time the code gets executed.

Define a Custom Function

If you want to generate a random string of a specific length using letters and numbers, you can create a custom function as follows:

import Foundation

func randomString(length: Int) -> String {
    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var randomString = ""
    for _ in 0 ..< length {
        let randomIndex = Int(arc4random_uniform(UInt32(letters.count)))
        let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
        randomString += String(letter)
    }
    return randomString
}

let s1 = randomString(length: 10)
let s2 = randomString(length: 20)
let s3 = randomString(length: 30)

print(s1)
print(s2)
print(s3)

Output:

ZwzAGh28Sh
UIGyNTEYXedKd4Yfddao
xIqcXywYbp8NhVLDFyURJQ89beWuEk

Using CryptoKit

If you need a more secure way to generate random strings, you can use the CryptoKit framework introduced in iOS 13.

Example:

import Foundation
import CryptoKit

func generateRandomString(length: Int) -> String {
    // each hexadecimal character represents 4 bits, so we need 2 hex characters per byte
    let byteCount = length / 2 
    
    var bytes = [UInt8](repeating: 0, count: byteCount)
    let result = SecRandomCopyBytes(kSecRandomDefault, byteCount, &bytes)
    guard result == errSecSuccess else {
        fatalError("Failed to generate random bytes: \(result)")
    }
    
    // convert to hex string
    let hexString = bytes.map { String(format: "%02x", $0) }.joined()
    let paddedHexString = hexString.padding(toLength: length, withPad: "0", startingAt: 0)
    return paddedHexString
}


print(generateRandomString(length: 5))
print(generateRandomString(length: 30))

Output (not consistent):

119f0
01615f4099c8f5c0e4ef5504165892

This approach uses a more secure random generator than the 2 preceding ones.