正在使用 Swift 开发命令行工具? 需要显示表格? 请继续阅读。
将依赖项添加到您的 Package.swift
文件
import PackageDescription
let package = Package(
name: "My awesome CLI tool"
dependencies: [
.package(
url: "https://github.com/JanGorman/Table",
from: "1.0.0"
)
]
)
import Table
func doSomething() throws {
let data = [
["0A", "0B", "0C"],
["1A", "1B", "1C"],
["2A", "2B", "2C"],
]
let table = try Table(data: data).table()
print(table)
}
结果会生成一个美观的表格
╔════╤════╤════╗
║ 0A │ 0B │ 0C ║
╟────┼────┼────╢
║ 1A │ 1B │ 1C ║
╟────┼────┼────╢
║ 2A │ 2B │ 2C ║
╚════╧════╧════╝
您可以通过传入 Configuration
来对齐表格行
import Table
func doSomething() throws {
let data = [
["0A", "0B", "0C"],
]
// Give alignment and a minimum width
let columns = [
Column(alignment: .left, width: 10),
Column(alignment: .center, width: 10),
Column(alignment: .right, width: 10)
]
let configuration = Configuration(columns: columns)
let table = try Table(data: data).table()
print(table)
}
结果如下
╔══════════╤══════════╤══════════╗
║0A │ 0B │ 0C║
╚══════════╧══════════╧══════════╝
Configuration
也允许填充
import Table
func doSomething() throws {
let data = [
["0A", "0B", "0C"],
]
let columns = [
Column(paddingLeft: 3, paddingRight: 4),
Column(paddingLeft: 8, paddingRight: 8),
Column(paddingLeft: 3, paddingRight: 4)
]
let configuration = Configuration(columns: columns)
let table = try Table(data: data).table()
print(table)
}
会得到
╔═════════╤══════════════════╤═════════╗
║ 0A │ 0B │ 0C ║
╚═════════╧══════════════════╧═════════╝
要为您的表格使用自定义边框,只需创建一个遵循 Border
协议的 struct
,并将其作为自定义 Configuration
的一部分传入。 例如
import Table
struct CustomBorder: Border {
public let topBody = "─"
public let topJoin = "┬"
public let topLeft = "┌"
public let topRight = "┐"
public let bottomBody = "─"
public let bottomJoin = "┴"
public let bottomLeft = "└"
public let bottomRight = "┘"
public let bodyLeft = "│"
public let bodyRight = "│"
public let bodyJoin = "│"
public let joinBody = "─"
public let joinLeft = "├"
public let joinRight = "┤"
public let joinJoin = "┼"
}
func doSomething() throws -> String {
…
let configuration = Configuration(border: CustomBorder(), columns: columns)
return try Table(data: data).table()
}
Table 根据 MIT 许可证发布。 有关详细信息,请参阅 LICENSE。