Closure Expressions in Swift
Level 3135 keystrokes
Passes short closures with $0 and $1 to sorted and map using trailing closure syntax: sorts in descending order and doubles each element.
Swift code
// The source array (1 appears twice)1let numbers = [3, 1, 4, 1, 5]// $0 > $1 puts larger values first; sorted returns a new array2let sorted = numbers.sorted { $0 > $1 }// numbers itself is unchanged, so map works on the original order3let doubled = numbers.map { $0 * 2 }// Prints [5, 4, 3, 1, 1]4print(sorted)// Prints [6, 2, 8, 2, 10]5print(doubled)Output
[5, 4, 3, 1, 1] [6, 2, 8, 2, 10]
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.× 2(× 2)× 2{× 2}× 2[× 1]× 1