Chapter 19, Bronze Challenge Solution

I moved the columnWidths[j] - item.count calculation into a constant, widthDelta. I then used the ternary operator to evaluate whether widthDelta has a negative value. If the column label’s width is less than the item’s width, then no padding is needed, and I assign 0 to paddingNeeded.

func printTable(_ dataSource: TabularDataSource &
                CustomStringConvertible) {
    print("Table: \(dataSource)")
    // Create a header row containing column headers
    var headerRow = "|"
    
    // Also keep track of the width of each column
    var columnWidths = [Int]()
    
    for i in 0 ..< dataSource.numberOfColumns {
        let columnLabel = dataSource.label(forColumn: i)
        let columnHeader = " \(columnLabel) |"
        headerRow += columnHeader
        columnWidths.append(columnLabel.count)
    }
    print(headerRow)
    
    for i in 0 ..< dataSource.numberOfRows {
        // Start the output string
        var out = "|"
        
        // Append each item in this row to the string
        for j in 0 ..< dataSource.numberOfColumns {
            let item = dataSource.itemFor(row: i, column: j)
            
            // Bronze challenge
            let widthDelta = columnWidths[j] - item.count
            let paddingNeeded = widthDelta > 0 ? widthDelta : 0
            
            let padding = repeatElement(" ", count:
                                            paddingNeeded).joined(separator: "")
            out += " \(padding)\(item) |"
        }
        
        // Done - print it!
        print(out)
    }
}

Bronze Challenge and Gold Challenge

func printTable(_ dataSource: TabularDataSource & CustomStringConvertible)
{
print(“Table: (dataSource)”)

//Create header row containing column headers
var headerRow = "|"
//Also keep track of the width of each column
var columnWidth = [Int]()

for i in 0..<dataSource.numberOfColumns
{
    let columnLabel = dataSource.label(forColumn: i)
    let columnHeader = " \(columnLabel) |"
    headerRow += columnHeader
    columnWidth.append(columnLabel.count)
}
print(headerRow)
for i in 0..<dataSource.numberOfRows
{
    // Start the output string
    var out = "|"
    
    //Append each item in this row to the string
    for j in 0..<dataSource.numberOfColumns
    {
        let item = dataSource.itemFor(row: i, column: j)
        
        if (item.count > columnWidth[j]) //GOLD CHALLENGE IF STATEMENT
        {
            columnWidth[j] = item.count
            
        }
        
        var paddingNeeded = columnWidth[j] - item.count //BRONZE CHALLENGE
        if paddingNeeded < 0 //BRONZE CHALLENGE IF STATEMENT
        {
            paddingNeeded = item.count
        }
        let padding = repeatElement(" ", count: paddingNeeded).joined(separator: "")
        out += " \(padding)\(item) |"
    }
    
    //Done - print it!
    print(out)
}

}