Color ouput with Swift command line tool

后端 未结 6 1827
萌比男神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:49

    Combining some of @Diego's answer, you can use Swift's new DefaultStringInterpolation structure to extend this decoration into your string literals–

    enum ASCIIColor: 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"
        case `default` = "\u{001B}[0;0m"
    }
    
    extension DefaultStringInterpolation {
        mutating func appendInterpolation(_ value: T, color: ASCIIColor) {
            appendInterpolation("\(color.rawValue)\(value)\(ASCIIColor.default.rawValue)")
        }
    }
    // USAGE:
    // "\("only this string will be green!", color: .green)"
    

提交回复
热议问题