Console

public protocol Console: Extendable

Protocol for powering styled Console I/O.

Output

Consoles can output stylized text via the ConsoleText struct.

console.output("Hello, " + "world!".consoleText(color: .green))

See ConsoleStyle for all available text style options.

There are also convenience methods for printing common styles.

console.info("Here is some information")

Input

Consoles can also request input from the user.

let answer = console.ask("How are you doing?")
print(answer)

Clear

Consoles can clear previously outputted content using clear(_:).

console.print("Hello!")
console.clear(.line) // delete hello

See pushEphemeral() method for clearing arbitrary chunks of output.

Other

Use the report(error:newLine:) method for reporting errors to the Console.

Get the Console’s current size using the size property.

  • The size of the Console window. Used for calculating lines printed and centering text.

    Declaration

    Swift

    var size: (width: Int, height: Int)
  • Returns a String of input read from the Console until a line feed character was found.

    let input = console.input(isSecure: false)
    print(input) // String
    

    Note

    The line feed character should not be included.

    Declaration

    Swift

    func input(isSecure: Bool) -> String

    Parameters

    secure

    If true, the input should not be shown while it is entered.

  • Outputs serialized ConsoleText to the Console.

    console.output("Hello, " + "world!".consoleText(color: .green))
    

    Declaration

    Swift

    func output(_ text: ConsoleText, newLine: Bool)

    Parameters

    output

    ConsoleText to serialize and print.

    newLine

    If true, the next output will be on a new line.

  • Clears previously printed Console output according to the ConsoleClear type given.

    Declaration

    Swift

    func clear(_ type: ConsoleClear)

    Parameters

    type

    ConsoleClear type to use, e.g., single line or whole screen.

  • Outputs an error to the Console’s error stream.

    Note

    This is stderr for most consoles.

    Declaration

    Swift

    func report(error: String, newLine: Bool)

    Parameters

    error

    Error String to output.

    newLine

    If true, the next error will be on a new line.

  • loadingBar(title:) Extension method

    Creates a new LoadingBar-based ActivityIndicator.

    Loading [                     ]
    

    The character will bounce from left to right while the bar is active.

    let loadingBar = console.loadingBar(title: "Loading")
    background {
        // complete the loading bar after 3 seconds
        console.blockingWait(seconds: 3)
        loadingBar.succeed()
    }
    // start the loading bar and wait for it to finish
    try loadingBar.start(on: ...).wait()
    

    Declaration

    Swift

    public func loadingBar(title: String) -> ActivityIndicator<LoadingBar>

    Parameters

    title

    Title to display alongside the loading bar.

    Return Value

    An ActivityIndicator that can start and stop the loading bar.

  • progressBar(title:) Extension method

    Creates a new ProgressBar-based ActivityIndicator.

    Downloading [========                ]
    

    The = characters represent the value of ProgressBar.currentProgress from 0…1

    let progressBar = console.progressBar(title: "Downloading")
    background {
        // increment the progress bar by 10% every 1/4 second
        // once progress is 100%, trigger success
        while true {
            if progressBar.activity.currentProgress >= 1 { break }
            progressBar.activity.currentProgress += 0.1
            console.blockingWait(seconds: 0.25)
        }
        progressBar.succeed()
    }
    // start the progress bar and wait for it to finish
    try progressBar.start(on: ...).wait()
    

    Declaration

    Swift

    public func progressBar(title: String) -> ActivityIndicator<ProgressBar>

    Parameters

    title

    Title to display alongside the loading bar.

    Return Value

    An ActivityIndicator that can start and stop the loading bar.

  • clear(lines:) Extension method

    Deletes lines that were previously printed to the terminal.

    console.print("Hello!")
    console.clear(lines: 1) // clears the previous print
    

    Declaration

    Swift

    public func clear(lines: Int)

    Parameters

    lines

    The number of lines to clear.

  • pushEphemeral() Extension method

    Pushes a new ephemeral console state. All text outputted to the console immidiately after this call can be cleared by using popEphemeral().

    This method can be called as many times as desired. Calls to popEphemeral() will work in reverse order.

    console.print("a")
    console.pushEphemeral()
    console.print("b")
    console.print("c")
    console.pushEphemeral()
    console.print("d")
    console.print("e")
    console.print("f")
    console.popEphemeral() // removes "d", "e", and "f" lines
    console.print("g")
    console.popEphemeral() // removes "b", "c", and "g" lines
    // just "a" has been printed now
    

    Declaration

    Swift

    public func pushEphemeral()
  • popEphemeral() Extension method

    Pops a previous ephemeral console state. All text outputted to the console immidiately after the last call to pushEphemeral() will be cleared.

    This method can be called once for each call to pushEphemeral().

    console.print("a")
    console.pushEphemeral()
    console.print("b")
    console.print("c")
    console.pushEphemeral()
    console.print("d")
    console.print("e")
    console.print("f")
    console.popEphemeral() // removes "d", "e", and "f" lines
    console.print("g")
    console.popEphemeral() // removes "b", "c", and "g" lines
    // just "a" has been printed now
    

    Declaration

    Swift

    public func popEphemeral()
  • didOutputLines(count:) Extension method

    This method allows the Console implementation to record how many lines have been printed so that pushEphemeral() and popEphemeral() knows how many lines to clear.

    This method should only be used by Console implementations.

    Declaration

    Swift

    public func didOutputLines(count: Int)
  • ask(_:isSecure:) Extension method

    Requests input from the console after displaying a prompt.

    let answer = console.ask("How are you doing?")
    console.output("You said: " + answer.consoleText())
    

    Input will be read until the first newline. See Console.input(isSecure:). The above code outputs:

    How are you doing?
    > great!
    You said: great!
    

    Declaration

    Swift

    public func ask(_ prompt: ConsoleText, isSecure: Bool = false) -> String

    Parameters

    prompt

    Text to display before asking for input.

    isSecure

    Return Value

    Input String. entered in response to the prompt.

  • choose(_:from:) Extension method

    Prompts the user to choose an item from the supplied array. The chosen item will be returned.

    let color = console.choose("Favorite color?", from: ["Pink", "Blue"])
    console.output("You chose: " + color.consoleText())
    

    The above code will output:

    Favorite color?
    1: Pink
    2: Blue
    >
    

    Upon answering, the prompt and options will be cleared from the console and only the output will remain:

    You chose: Blue
    

    This method calls choose(_:from:display:) using CustomStringConvertible to display each element.

    Declaration

    Swift

    public func choose<T>(_ prompt: ConsoleText, from array: [T]) -> T
        where T: CustomStringConvertible

    Parameters

    prompt

    ConsoleText prompt to display to the user before listing options.

    array

    Array of CustomStringConvertible items to choose from.

    Return Value

    Element from array that the user chose.

  • choose(_:from:display:) Extension method

    Prompts the user to choose an item from the supplied array. The chosen item will be returned.

    let color = console.choose("Favorite color?", from: ["Pink", "Blue"])
    console.output("You chose: " + color.consoleText())
    

    The above code will output:

    Favorite color?
    1: Pink
    2: Blue
    >
    

    Upon answering, the prompt and options will be cleared from the console and only the output will remain:

    You chose: Blue
    

    See choose(_:from:) which uses CustomStringConvertible to display each element.

    Declaration

    Swift

    public func choose<T>(_ prompt: ConsoleText, from array: [T], display: (T) -> ConsoleText) -> T

    Parameters

    prompt

    ConsoleText prompt to display to the user before listing options.

    array

    Array of CustomStringConvertible items to choose from.

    display

    A closure for converting each element of array to a ConsoleText for display.

    Return Value

    Element from array that the user chose.

  • confirm(_:) Extension method

    Requests yes / no confirmation from the user after a prompt.

    if console.confirm("Delete everything?") {
        console.warning("Deleting everything!")
    } else {
        console.print("OK, I won't.")
    }
    

    The above code outputs:

    Delete everything?
    > no
    OK, I won't.
    

    This method will attempt to convert the response into a Bool using String.bool. It will continue to ask until the result is a proper format, providing additional help after a few failed attempts.

    See Console.confirmOverride for enabling automatic answers to all confirmation prompts.

    Declaration

    Swift

    public func confirm(_ prompt: ConsoleText) -> Bool

    Parameters

    prompt

    ConsoleText to display before the confirmation input.

    Return Value

    true if the user answered yes, false if no.

  • confirmOverride Extension method

    If set, all calls to confirm(_:) will use this value instead of asking the user.

    Declaration

    Swift

    public var confirmOverride: Bool?
  • center(_:padding:) Extension method

    Centers a String according to this console’s size.

    Declaration

    Swift

    public func center(_ string: String, padding: Character = " ") -> String

    Parameters

    string

    String to center.

    padding

    Character to use for padding, " " by default.

    Return Value

    String with padding added so that it is centered.

  • center(_:padding:) Extension method

    Centers an array of Strings according to this console’s size.

    Declaration

    Swift

    public func center(_ strings: [String], padding: Character = " ") -> [String]

    Parameters

    strings

    String to center.

    padding

    Character to use for padding, " " by default.

    Return Value

    String with padding added so that it is centered.

  • output(_:) Extension method

    Outputs serialized ConsoleText to the Console.

    console.output("Hello, " + "world!".consoleText(color: .green))
    

    Declaration

    Swift

    public func output(_ text: ConsoleText)

    Parameters

    output

    ConsoleText to serialize and print.

  • output(_:style:newLine:) Extension method

    Outputs a String to the Console with the specified ConsoleStyle style.

    console.print("Hello, world!", style: .plain)
    

    Declaration

    Swift

    public func output(_ string: String, style: ConsoleStyle, newLine: Bool = false)

    Parameters

    string

    String to print.

    style

    ConsoleStyle to use for the string.

    newLine

    If true, the next output will be on a new line.

  • print(_:newLine:) Extension method

    Outputs a String to the Console with ConsoleStyle.plain style.

    console.print("Hello, world!")
    

    Declaration

    Swift

    public func print(_ string: String = "", newLine: Bool = true)

    Parameters

    string

    String to print.

    newLine

    If true, the next output will be on a new line.

  • info(_:newLine:) Extension method

    Outputs a String to the Console with ConsoleStyle.info style.

    console.info("Vapor is the best.")
    

    Declaration

    Swift

    public func info(_ string: String = "", newLine: Bool = true)

    Parameters

    string

    String to print.

    newLine

    If true, the next output will be on a new line.

  • success(_:newLine:) Extension method

    Outputs a String to the Console with ConsoleStyle.success style.

    console.success("It works!")
    

    Declaration

    Swift

    public func success(_ string: String = "", newLine: Bool = true)

    Parameters

    string

    String to print.

    newLine

    If true, the next output will be on a new line.

  • warning(_:newLine:) Extension method

    Outputs a String to the Console with ConsoleStyle.warning style.

    console.warning("Watch out...")
    

    Declaration

    Swift

    public func warning(_ string: String = "", newLine: Bool = true)

    Parameters

    string

    String to print.

    newLine

    If true, the next output will be on a new line.

  • error(_:newLine:) Extension method

    Outputs a String to the Console with ConsoleStyle.error style.

    console.error("Uh oh...")
    

    Declaration

    Swift

    public func error(_ string: String = "", newLine: Bool = true)

    Parameters

    string

    String to print.

    newLine

    If true, the next output will be on a new line.

  • blockingWait(seconds:) Extension method

    Blocks the current thread for the specified number of seconds.

    console.blockingWait(seconds: 3.14)
    

    Warning

    Do not use this method on an EventLoop. It is for testing purposes only.

    Declaration

    Swift

    public func blockingWait(seconds: Double)

    Parameters

    seconds

    The number of seconds to wait for.