Back to questions
JuniorTheoryCommon
What does the program print?
let words = ["4", "two", "6"]
let total = words.compactMap { Int($0) }.reduce(0, +)
print(total)10
- Expecting it not to compile, as with
map:mapwould give[Int?], whichreduce(0, +)cannot add up, butcompactMapdropsniland returns[Int]. - Expecting
12: thinkingIntunderstands number words.Int("two")givesnil, so only4and6are added.
- What does
words.map { Int($0) }give, and why can it not be summed withreduce(0, +)? - How would you count the words that are not numbers?