Last active
February 13, 2024 01:55
-
-
Save benigumocom/1320e95fb2c9a9309297a815c027059e to your computer and use it in GitHub Desktop.
【Swift】配列をコンソールにテーブル形式で表示する 👉 https://android.benigumo.com/20240213/show-table/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array where Element: Collection, Element.Index == Int { | |
func showTable() { | |
transposed() | |
.map { $0.map { "\($0)" } } | |
.map { | |
let max = $0.map { $0.countAsHalfWidth }.max()! | |
return $0.map { $0.padding(length: max) } | |
} | |
.transposed() | |
.map { "| " + $0.joined(separator: " | ") + " |" } | |
.forEach { | |
print($0) | |
} | |
} | |
func transposed() -> [[Element.Element]] { | |
let cols = 0 ..< (self.first?.count ?? 0) | |
let rows = 0 ..< self.count | |
return cols.map { col in | |
rows.map { row in | |
self[row][col] | |
} | |
} | |
} | |
} | |
extension String { | |
var countAsHalfWidth: Int { | |
return Array(self) | |
.map { $0.isASCII ? 1 : 2 } | |
.reduce(0, +) // sum | |
} | |
func padding(length: Int, pad: String = " ") -> String { | |
return String( | |
repeating: pad, | |
count: length - countAsHalfWidth | |
) + self | |
} | |
} | |
// ex. | |
let data = [ | |
[1, 2, 3], | |
["いぬ", "ねこ", "さる"], | |
["dog", "cat", "monkey"] | |
] | |
print(data) | |
// [[1, 2, 3], ["いぬ", "ねこ", "さる"], ["dog", "cat", "monkey"]] | |
data.showTable() | |
// | 1 | 2 | 3 | | |
// | いぬ | ねこ | さる | | |
// | dog | cat | monkey | |
Author
benigumocom
commented
Feb 12, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment