Map
Part of the Logic & Flow section of Coddy's Swift journey — lesson 23 of 56.
map takes a closure and applies it to every element, returning a new array of the results. The new array has the same length as the source.
let nums = [1, 2, 3, 4]
let doubled = nums.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8]$0 is shorthand for the closure's first parameter. The longer form spells out the parameter name and the return type:
let doubled = nums.map { (n: Int) -> Int in
return n * 2
}map can also change the element type. Mapping an [Int] through a closure that returns String gives you a [String]:
let labels = nums.map { "#\($0)" }
print(labels) // ["#1", "#2", "#3", "#4"]Challenge
EasyRead a single line of input: a comma-separated list of integers (temperatures in Fahrenheit).
Convert each one to Celsius using the formula C = (F - 32) * 5 / 9 in integer arithmetic (truncate toward zero, no decimals). Print, on separate lines:
- The Celsius temperatures, joined with
, - One label per temperature with the prefix
F=<f> C=<c>, joined with;
Use map for both lines.
For input 32,212,98,0, the output is:
0,100,36,-17
F=32 C=0;F=212 C=100;F=98 C=36;F=0 C=-17Cheat sheet
map applies a closure to every element and returns a new array of the same length:
let nums = [1, 2, 3, 4]
let doubled = nums.map { $0 * 2 } // [2, 4, 6, 8]$0 is shorthand for the closure's first parameter. Explicit form:
let doubled = nums.map { (n: Int) -> Int in
return n * 2
}map can change the element type (e.g. [Int] → [String]):
let labels = nums.map { "#\($0)" } // ["#1", "#2", "#3", "#4"]Try it yourself
let f = readLine()!.components(separatedBy: ",").map { Int($0)! }
// TODO: line 1 = celsius joined with ","
// TODO: line 2 = labels "F=<f> C=<c>" joined with ";"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check