Skip to content

Instantly share code, notes, and snippets.

@AppleBetas
Last active July 10, 2016 03:33
Show Gist options
  • Save AppleBetas/3f4864f2440d409c6b797879edd7f106 to your computer and use it in GitHub Desktop.
Save AppleBetas/3f4864f2440d409c6b797879edd7f106 to your computer and use it in GitHub Desktop.
Colour.swift - A great way to add quick colours to command-line Swift apps with a quick and easy API
//
// Colour.swift
//
// Created by AppleBetas on 2016-07-09.
// Copyright © 2016 AppleBetas. All rights reserved.
//
/*
Example usage:
In normal print command:
print("\(Colour.blue.ansi)Test!")
print("\(BackgroundColour.blue.ansi)Test!")
let design = ColourDesign(foreground: .blue, background: .yellow)
print("\(design.ansi)Test!")
Custom print commands (recommended):
print("Test!", colour: .blue)
print("Test!", colour: nil, background: .blue)
print("Test!", colour: .blue, background: .yellow)
let design = ColourDesign(foreground: .blue, background: .yellow)
print("Test!", design: design)
*/
import Foundation
enum Colour {
case black, red, green, yellow, blue, magenta, cyan, white, reset
var code: Int {
get {
switch self {
case black:
return 30
case red:
return 31
case green:
return 32
case yellow:
return 33
case blue:
return 34
case magenta:
return 35
case cyan:
return 36
case white:
return 37
case reset:
return 39
}
}
}
var ansi: String {
return "\u{001B}[0;\(self.code)m"
}
}
enum BackgroundColour {
case black, red, green, yellow, blue, magenta, cyan, white, reset
var code: Int {
get {
switch self {
case black:
return 40
case red:
return 41
case green:
return 42
case yellow:
return 43
case blue:
return 44
case magenta:
return 45
case cyan:
return 46
case white:
return 47
case reset:
return 49
}
}
}
var ansi: String {
return "\u{001B}[\(self.code);0m"
}
}
struct ColourDesign {
var foreground: Colour?, background: BackgroundColour?
var ansi: String {
get {
return "\u{001B}[\(self.background?.code ?? 0);\(self.foreground?.code ?? 0)m"
}
}
static var reset: ColourDesign {
get {
return ColourDesign(foreground: .reset, background: .reset)
}
}
}
func print(_ text: String, design: ColourDesign) {
print("\(design.ansi)\(text)\(ColourDesign.reset.ansi)")
}
func print(_ text: String, colour: Colour?, background: BackgroundColour? = nil) {
let design = ColourDesign(foreground: colour, background: background)
print(text, design: design)
}
@nullpixel
Copy link

Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment