LoginSignup
3
3

More than 1 year has passed since last update.

SwiftのCLIで出力に色をつける

Last updated at Posted at 2021-11-22

Xcode上のコンソールには色をつけて表示することができませんが、ターミナルで実行するCLIには色をつけて表示することができます。

実装

extension String {
    enum ConsoleColor: Int {
        case black = 30
        case red
        case green
        case yellow
        case blue
        case magenta
        case cyan
        case white
    }

    enum ConsoleStyle: Int {
        case `default`
        case bold
        case thin
        case italic
        case underline
        case blink
        case fastBrink
        case reverseFrontBack
        case hidden
        case cancel
    }

    func colored(_ color: ConsoleColor, style: ConsoleStyle = .default) -> String {
        "\u{001B}[\(style.rawValue);\(color.rawValue)m\(self)\u{001B}[0m"
    }
}

使い方

let text = "This is bold yellow text\n".colored(.yellow, style: .bold)
    + "This is blue background text\n".colored(.green, style: .reverseFrontBack)
    + "This is default color text"
print(text)

結果

スクリーンショット 2021-11-22 15.03.25.png

参考までに、こちらのリポジトリで使用しております。
https://github.com/s2mr/memo-cli

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3