Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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 5 hours ago by avibootz
...