A Swift Package for converting between hex color strings and native Apple platform color types (UIColor, NSColor, and SwiftUI Color).
- ✅ Convert hex strings to native color objects
- ✅ Convert native color objects to hex strings
- ✅ Support for 3, 4, 6, and 8 character hex formats
- ✅ Alpha channel support
- ✅ Optional (
?) and throwing APIs - ✅ Automatic
#prefix handling - ✅ Swift 5.10+ compatibility
- ✅ Comprehensive XCTest test coverage
Add the following to your Package.swift file:
dependencies: [
.package(url: "https://github.com/edgeengineer/color-hex.git", from: "0.0.1")
]Or add it through Xcode: File → Add Package Dependencies → Enter the repository URL.
import ColorHex
// Create HexColor from string
let hexColor = HexColor(hex: "#FF0000") // Optional initializer
let hexColor2 = try HexColor(throwingHex: "#FF0000") // Throwing initializer
// Convert to hex string
let hexString = hexColor?.hexString() // "#FF0000"
let hexStringWithAlpha = hexColor?.hexString(includeAlpha: true) // "#FF0000FF"import ColorHex
// Optional API
let color = "#FF0000".hexColor()
// Throwing API
let color2 = try "#FF0000".throwingHexColor()import UIKit
import ColorHex
// Create UIColor from hex
let redColor = UIColor(hex: "#FF0000")
// Convert UIColor to hex
let uiColor = UIColor.red
let hexString = uiColor.hexString // "#FF0000"
let hexColor = uiColor.hexColorimport AppKit
import ColorHex
// Create NSColor from hex
let redColor = NSColor(hex: "#FF0000")
// Convert NSColor to hex
let nsColor = NSColor.red
let hexString = nsColor.hexString // "#FF0000"
let hexColor = nsColor.hexColorimport SwiftUI
import ColorHex
// Create SwiftUI Color from hex
let redColor = Color(hex: "#FF0000")
// Convert SwiftUI Color to hex
let color = Color.red
let hexString = color.hexString // "#FF0000"
let hexColor = color.hexColor| Format | Example | Description |
|---|---|---|
| RGB (3 digits) | #F0F |
Short form, expanded to #FF00FF |
| RGBA (4 digits) | #F0FA |
Short form with alpha |
| RGB (6 digits) | #FF00FF |
Standard RGB format |
| RGBA (8 digits) | #FF00FFAA |
RGB with alpha channel |
All formats support optional # prefix and are case-insensitive.
The throwing API provides specific error types:
do {
let color = try HexColor(throwingHex: "invalid")
} catch HexColorError.invalidCharacters {
print("Contains non-hex characters")
} catch HexColorError.invalidLength {
print("Invalid length (must be 3, 4, 6, or 8 characters)")
} catch HexColorError.invalidFormat {
print("Invalid format")
}- Swift 5.10+
- Xcode 15.0+
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.