便捷工具,用于用 Swift CLI 展示文本并选择提示

SwiftPrompt

方便的方法在 swift CLI 中呈现文本输入和选项选择器提示。

屏幕截图

正在进行的组

用法

提示组:

SwiftPrompt 允许单独使用其实用程序,但是,最好将提示视为“组”,因为这是 SwiftPrompt 绘制更美观的终端输出的地方:

例如,如果您让用户注册名为“水果”的服务,您可以在通用标头下呈现一组输入提示:

import SwiftPrompt

Prompt.startPromptGroup(title: "Sign Up to Fruits:")

// present prompts

// Write general update to group
Prompt.writeGroupUpdate(title: "Registering account...")

// Close out the group and write outcome
Prompt.endPromptGroup(title: "Account Registered")

文本提示:

要请求标准文本输入,您可以使用 Prompt.textInput

let emailAddress = Prompt.textInput(
    question: "What is your email address?",
    placeholder: "This input will have not-empty validation",
    isSecureEntry: false,
    validator: {
        // no validation
        return .valid
    }
)

您还可根据需要自定义验证逻辑,例如,如果您想确保输入不能为空:

let emailAddress = Prompt.textInput(
    question: "What is your email address?",
    placeholder: "This input will have not-empty validation",
    isSecureEntry: false,
    validator: {
        // Ensure input is not empty
        if !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            return .valid
        } else {
            return .invalid(message: "Please enter something")
        }
    }
)

您还可以将 isSecureEntry 设置为 true,如果想将输入屏蔽为 符号:

// Ask for password
let password = Prompt.textInput(
    question: "Enter a password:",
    placeholder: "Enter something secure with at least 8 characters