Sling Academy
Home/Swift/3 Ways to Generate Random Strings in Swift

3 Ways to Generate Random Strings in Swift

Last updated: February 23, 2023

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.

Next Article: 2 Ways to Reverse a String in Swift

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)