Array Map in Swift
Level 3143 keystrokes
Uses map to build new arrays from an array: one with the squares and one with strings. The original array is unchanged.
Swift code
// The source array1let numbers = [1, 2, 3, 4, 5]// map applies the closure to each element: [1, 4, 9, 16, 25]2let squared = numbers.map { $0 * $0 }// The result type can differ: here map returns [String]3let strings = numbers.map { "Number: \($0)" }// Prints [1, 4, 9, 16, 25]4print(squared)// Strings in an array are printed with quotes: ["Number: 1", ...]5print(strings)Output
[1, 4, 9, 16, 25] ["Number: 1", "Number: 2", "Number: 3", "Number: 4", "Number: 5"]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
,× 4(× 3)× 3=× 3$× 3.× 2"× 2{× 2}× 2:× 1