Skip to content

Instantly share code, notes, and snippets.

@kean
Last active December 25, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kean/d0c102aa6cfd06b25cf16c09923de1e9 to your computer and use it in GitHub Desktop.
Save kean/d0c102aa6cfd06b25cf16c09923de1e9 to your computer and use it in GitHub Desktop.
Converts UIColor init to a color literal
import Foundation
/// Input:
///
/// public static let purple = UIColor(red: 74/255, green: 21/255, blue: 153/255, alpha: 1.0)
///
/// Output:
///
/// #4A1599 (74, 21, 153)
/// public static let purple = #colorLiteral(red: 0.2901960784, green: 0.0823529412, blue: 0.6, alpha: 1)
for argument in CommandLine.arguments.dropFirst() {
for line in argument.split(separator: "\n") where !line.isEmpty {
print(try convert(String(line)))
}
}
func convert(_ input: String) throws -> String {
let regex = /public static let (\w+) = UIColor\(red: (\d+).*?, green: (\d+).*?, blue: (\d+).*?\)/
guard let (_, name, red, green, blue) = try regex.firstMatch(in: input)?.output else {
fatalError("Failed to match input")
}
guard let red = Int(red), let green = Int(green), let blue = Int(blue) else {
fatalError("Failed to parse color")
}
func render(_ color: Int) -> String {
(Double(color) / 255).formatted(.number.precision(
.integerAndFractionLength(integerLimits: 1...1, fractionLimits: 1...10)
))
}
func hex(from value: Int) -> String {
String(format: "%02X", value)
}
let hex = "#\(hex(from: red))\(hex(from: green))\(hex(from: blue))"
return """
/// \(hex) (\(red), \(green), \(blue))
public static let \(name) = #colorLiteral(red: \(render(red)), green: \(render(green)), blue: \(render(blue)), alpha: 1)
"""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment