Map(_:) method explanation


#1

The code on pg. 724 calls on the map method. The book explains that, [quote]“First, you use rowLabels.map to create a new array containing the width of each label.”[/quote]. I’m lost in what exactly is happening. Why do we have to include the map method? I took it out and I got errors, why?

[code]func padding(amount: Int) -> String {
var paddingString = ""
for _ in 0 …< amount {
paddingString += " "
}
return paddingString
}

func printTable(rowLabels: [String], data: [[Int]]) {
// Create an array of the width of each row label
let rowLabelWidths = rowLabels.map { $0.characters.count } //How does this line work?

// Determine length of longest row label
guard let maxRowLabelWidth = rowLabelWidths.maxElement() else {
    return
}
    
for (i, row) in data.enumerate() {
     // Pad the row lavel out so they are all the same length
    let paddingAmount = maxRowLabelWidth - rowLabelWidths[i]
    var out = rowLabels[i] + padding(paddingAmount) + " |"
    
    // Append each item in this row to our string
    for item in row {
        out += " \(item) |"
    }

//Done - print it!
print(out)
}

}

let rowLabels = [“Joe”, “Karen”, “Fred”]
let data = [
[30, 6],
[40, 18],
[50, 20],
]

printTable(rowLabels, data: data)[/code]


#2

[quote=“sisball8”]func printTable(rowLabels: [String], data: [[Int]]) { // Create an array of the width of each row label let rowLabelWidths = rowLabels.map { $0.characters.count } //How does this line work? [/quote]
map(_:slight_smile: is a function that you can use to transform an array’s contents. You map an array’s contents from one value to another and put these new values into an new array. Because map(_:slight_smile: is a higher order function, you provide it with another function that tells it how to transform the array’s contents.” (p. 124)

rowLabels is an array of String values … [String], and we want to know their lengths as an array of Int values… [Int]. You can perhaps think of this map function as a shortcut for

var tempLabelWidths: [Int] = [] for i in 0 ..< rowLabels.count { tempLabelWidths.append(rowLabels[i].characters.count) } let rowLabelWidths: [Int] = tempLabelWidths