How to generate a series of unique HEX colors in Swift

1 Answer

0 votes
import Foundation

/// Generates a single random color channel (0...255)
func randomChannel() -> Int {
    // Int.random(in:) is Swift’s idiomatic RNG
    Int.random(in: 0...255)
}

/// Builds a full random HEX color, e.g. "#a3f09c"
func randomHexColor() -> String {
    let r: Int = randomChannel()
    let g: Int = randomChannel()
    let b: Int = randomChannel()

    // Format each channel as two-digit lowercase hex
    return String(format: "#%02x%02x%02x", r, g, b)
}

/// Generates N unique random HEX colors
func generateRandomUniqueHexColors(_ count: Int) -> [String] {
    // Set ensures uniqueness automatically
    var colors: Set<String> = []

    // Keep generating until we have the desired number
    while colors.count < count {
        colors.insert(randomHexColor())
    }

    // Convert Set → Array
    return Array(colors)
}

// Example usage
let n: Int = 12
let colors: [String] = generateRandomUniqueHexColors(n)

print("Generated HEX colors:")
colors.forEach { print($0) }


/*
run:

Generated HEX colors:
#d67f67
#e8a0e3
#3b1e3c
#faddbf
#59820c
#8629ee
#ef313d
#fc8c01
#5c9696
#c58a7c
#39ec0c
#28dcf5

*/

 



answered Aug 24 by avibootz
...