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 by avibootz

Related questions

1 answer 43 views
2 answers 42 views
2 answers 37 views
2 answers 42 views
2 answers 43 views
...