Swift aligned plain-text table renderer
Swift
import Foundation
func renderTable(headers: [String], rows: [[String]]) -> String {
let all = [headers] + rows
let widths = headers.indices.map { column in
all.map { $0[column].count }.max() ?? 0
}
func line(_ cells: [String]) -> String {
zip(cells, widths).map { cell, width in
cell.padding(toLength: width, withPad: " ", startingAt: 0)
}.joined(separator: " | ")
}
let separator = widths.map { String(repeating: "-", count: $0) }.joined(separator: "-+-")
return ([line(headers), separator] + rows.map(line)).joined(separator: "\n")
}