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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to convert from HEX color to RGB in Swift

1 Answer

0 votes
import Foundation

func hexToRGB(hex: String) -> (red: Int, green: Int, blue: Int)? {
    var formattedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines)
    formattedHex = formattedHex.replacingOccurrences(of: "#", with: "")

    if formattedHex.count == 3 {
        formattedHex = formattedHex.map { String(repeating: $0, count: 2) }.joined()
    }

    guard formattedHex.count == 6,
          let hexValue = Int(formattedHex, radix: 16) else { return nil }

    let red = (hexValue >> 16) & 0xFF
    let green = (hexValue >> 8) & 0xFF
    let blue = hexValue & 0xFF

    return (red, green, blue)
}

if let rgb = hexToRGB(hex: "#FF05A3") {
    print("RGB values - Red: \(rgb.red), Green: \(rgb.green), Blue: \(rgb.blue)")
} else {
    print("Invalid HEX value!")
}

if let rgb = hexToRGB(hex: "#f00") {
    print("RGB values - Red: \(rgb.red), Green: \(rgb.green), Blue: \(rgb.blue)")
} else {
    print("Invalid HEX value!")
}

 
 
/*
run:
      
RGB values - Red: 255, Green: 5, Blue: 163
RGB values - Red: 255, Green: 0, Blue: 0
      
*/

 



answered Mar 7, 2025 by avibootz

Related questions

1 answer 78 views
2 answers 97 views
2 answers 71 views
2 answers 78 views
2 answers 84 views
...