Console Overview

本指引将简单介绍 Console (控制台) 模块, 向你展示如何格式化输出文本和请求用户输入.

Terminal

名为 Terminal (终端)Console (控制台) 协议的默认实现供你使用.

  1. let terminal = Terminal()
  2. print(terminal is Console) // true
  3. terminal.print("Hello")

本指引的剩余部分将假设一个通用的 控制台. 但直接使用 终端 也可以实现. 你可以使用任何可用的 容器 来创建一个控制台.

  1. let console = try req.make(Console.self)
  2. console.print("Hello")

Output

控制台 提供了集中输出字符串的便捷方法, 比如 print(_:)warning(_:). 所有这些函数最终都调用 output(_:), 最强大的输出函数. 这个函数接受 控制台, 它支持独立样式的字符串组件.

  1. /// Prints "Hello, world", but the word 'world' is blue.
  2. console.output("Hello, " + "world".consoleText(color: .blue))

你可以根据需要组合多个不同样式的片段到 ConsoleText (控制台文本) 中. 所有输出文本的 控制台 函数都应该有一个重载来接受 控制台文本.

Input

控制台 提供几种请求用户输入的函数, 最基本的是 input(isSecure:).

  1. /// Accepts input from the terminal until the first newline.
  2. let input = console.input()
  3. console.print("You wrote: \(input)")

Ask

使用 ask(_:) 为用户提供提示和输入指示器.

  1. /// Outputs the prompt then requests input.
  2. let name = console.ask("What is your name?")
  3. console.print("You said: \(name)")

上述代码会输出:

  1. What is your name?
  2. > Vapor
  3. You said: Vapor

Confirm

使用 confirm(_:) 为用户提供 是/否 输入.

  1. /// Prompts the user for yes / no input.
  2. if console.confirm("Are you sure?") {
  3. // they are sure
  4. } else {
  5. // don't do it!
  6. }

上述代码会输出:

  1. Are you sure?
  2. y/n> yes

note

confirm(_:) 将继续提示用户, 直到用户回复 yes 或 no.