> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/collections/collection/collection.columnwidths.md).

# collection.columnWidths

{% tabs %}
{% tab title="🌀 Collection" %}
💾 程式： [replit](https://replit.com/@pegasusroe/Swift-Playground#Extenions/Collection+.swift)        ⬆️ 需要： [.allElementsSameLength](/ios/swift/collections/collection/collection.allelementssamelength.md)

````swift
// ┌──────────────────────────────────┐
// │    Collection + .columnWidths    │
// └──────────────────────────────────┘

extension Collection where 
    Element: Collection,            // each element is Collection, e.g. Array.
    Element.Index == Int,           // each element is Int indexed (column index).
    Element.Element: Collection     // each cell is Collection (has `count`), e.g. String.
{
    /// determine the max length (count) in every column of a 2D array of data.
    ///
    /// ### Explanation:
    /// ```
    ///   typealias Data  = [[String]]   // Data is Array, which is Collection.
    ///   typealias Row   = [String]     // Row == Data.Element, Array (Int indexed).
    ///   typealias Value = String       // Value == Row.Element, String, which is Collection too
    /// ```
    /// ### Example:
    /// - `[["a", "bc", "def"], ["ab", "cde", "f"]].columnWidths == Optional([2, 3, 3])`
    /// - `[["a", "b", "c"], ["a"]].columnWidths == nil`
    public var columnWidths: [Int]? {
        
        guard 
            allElementsSameLength,       // all rows same length
            let firstRow = first,        // data must at least have one row
            !firstRow.isEmpty            // row must at least have one cell
        else {
            return nil
        }
        
        // for each column (at index j), find that column's max string length.
        // every column contains at least one string, so max length (max()) can't be nil.
        return (0 ..< firstRow.count).map { j in 
            self                                // collection of elements (rows)
                .map { row in row[j].count }    // array of j-th elements' lengths
                .max()!                         // ⭐ force unwrap (max string length)
        }
    }
}
````

{% endtab %}

{% tab title="👥 相關" %}

* uses [collection.allElementsSameLength](/ios/swift/collections/collection/collection.allelementssamelength.md).
* used by [Logger](/ios/swift/debugging/logger.md) (in .<mark style="color:purple;">**table**</mark>() method).
  {% endtab %}
  {% endtabs %}
