Skip to content
ColorTokensKitby Penguin Design Ventures
Contents
Function

.getHexString()

Log a color or hand it to a design tool as an sRGB hex string, with alpha when it's translucent.

Updated View as Markdown

Log a color or hand it to a design tool as hex with getHexString(). It takes nothing and returns six uppercase digits with no #, or eight with alpha last when the color is translucent:

swift
let brandColor = Color(hex: "#00B386")

brandColor.getHexString()                 // "00B386"
brandColor.opacity(0.5).getHexString()    // "00B38680", alpha last

A stop beyond sRGB#

Hex can only hold sRGB colors, so getHexString() clamps each channel of a Display P3 color into sRGB. The hex is a close sRGB color, not the stop itself:

swift
let fill = brand._600                 // a stop of the travel app's brand, beyond sRGB
fill.toRGB()                          // RGBColor(r: -0.178, g: 0.527, b: 0.372)
fill.toColor().getHexString()         // "00865F", with red clamped to 0

To pass such a color on without losing it, keep its name or its toRGB() value, not its hex. This wiki labels palette colors with Display P3 hex, the way an iPhone shows them, so its labels don't match getHexString() even inside sRGB.

Round trips through hex#

Color(hex: color.getHexString()) gives back the same color only when the color is opaque and inside sRGB. Color(hex:) reads alpha first and getHexString() writes it last, so for a translucent color, move the last two digits to the front before reading it back.

Tokens#

A token has two values, and getHexString() reads one: on iOS 17, macOS 14 and later, the light-mode value. To log a token's dark-mode color, find the stop it uses in dark mode in understanding semantic tokens and convert that stop.

How it behaves#

Each channel is clamped to 0 to 1 and rounded to the nearest of 256 steps. Alpha is added only when it isn't 1.

API#

swift
public extension Color {
    func getHexString() -> String   // "00B386", or "00B38680" with alpha last when translucent
}

It takes no parameters and returns an sRGB hex string: six uppercase digits with no #, or eight when the color isn't opaque.

Sources#

See also

  • Color(hex:) Turn a hex value from your design file into a SwiftUI color, with or without transparency.
  • .toRGB() Read a color's red, green and blue channels, even past sRGB, to hand to other graphics code.
  • .getLCHString() Log a color's lightness, chroma and hue in one short line, to check a color at a glance.
  • Fitting colors into Display P3 Stay inside Display P3 without losing contrast: chroma drops, lightness holds.