Color ouput with Swift command line tool

后端 未结 6 1882
萌比男神i
萌比男神i 2021-02-01 05:21

I\'m writing a command line tool with Swift and I\'m having trouble displaying colors in my shell. I\'m using the following code:

println(\"\\033[31;32mhey\\033         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 05:48

    Based on @cyt answer, I've written a simple enum with these colors and also overloaded + operator so you can print using that enum.

    It's all up on Github, but it's really that simple:

    enum ANSIColors: String {
        case black = "\u{001B}[0;30m"
        case red = "\u{001B}[0;31m"
        case green = "\u{001B}[0;32m"
        case yellow = "\u{001B}[0;33m"
        case blue = "\u{001B}[0;34m"
        case magenta = "\u{001B}[0;35m"
        case cyan = "\u{001B}[0;36m"
        case white = "\u{001B}[0;37m"
    
        func name() -> String {
            switch self {
            case .black: return "Black"
            case .red: return "Red"
            case .green: return "Green"
            case .yellow: return "Yellow"
            case .blue: return "Blue"
            case .magenta: return "Magenta"
            case .cyan: return "Cyan"
            case .white: return "White"
            }
        }
    
        static func all() -> [ANSIColors] {
            return [.black, .red, .green, .yellow, .blue, .magenta, .cyan, .white]
        }
    }
    
    func + (let left: ANSIColors, let right: String) -> String {
        return left.rawValue + right
    }
    
    // END
    
    
    // Demo:
    
    for c in ANSIColors.all() {
        println(c + "This is printed in " + c.name())
    }
    

提交回复
热议问题