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 random color in RGB format with Swift

2 Answers

0 votes
import Foundation

func generateRandomRGBColor() {
    let red = Int.random(in: 0...255)
    let green = Int.random(in: 0...255)
    let blue = Int.random(in: 0...255)

    print("Random RGB Color: rgb(\(red), \(green), \(blue))")
}

generateRandomRGBColor()



/*
run:

Random RGB Color: rgb(178, 48, 107)

*/

 



answered Oct 9, 2025 by avibootz
0 votes
/*
    Generate a random color in RGB format: rgb(R, G, B)
    This program demonstrates how numbers and bits are used
    to produce valid 8‑bit channel values.
*/

import Foundation

/// Create a random 8‑bit integer (0–255).
/// Int.random(in:) returns a value in the given range.
/// 256 (2^8) gives exactly one byte of color data.
func randomChannel() -> Int {
    // 8 bits → values from 0 to 255
    Int.random(in: 0 ..< 256)
}

/// Produce a random RGB color by combining the channels.
func generateRandomRGB() -> (r: Int, g: Int, b: Int, rgb: String) {
    let r = randomChannel()   // Red channel (8 bits)
    let g = randomChannel()   // Green channel (8 bits)
    let b = randomChannel()   // Blue channel (8 bits)

    // Construct the CSS-style RGB string
    let rgb = "rgb(\(r), \(g), \(b))"

    return (r, g, b, rgb)
}

// Run the program
let result = generateRandomRGB()

print("Red (8 bits):", result.r)
print("Green (8 bits):", result.g)
print("Blue (8 bits):", result.b)
print("RGB color:", result.rgb)


/*
run:

Red (8 bits): 162
Green (8 bits): 168
Blue (8 bits): 115
RGB color: rgb(162, 168, 115)

*/

 



answered 1 day ago by avibootz
...