Joseph Jude

Technology, Psychology, and Story Telling

Swift Challenge 006: Stringify even numbers

Posted: Tags: code,swift

Challenge: Take an array of numbers, concatenate the even numbers as a string

Logic: modulo 2 will separate the even numbers; convert the number to string; then concatenate

Code:


let input = [10,15,34,100,23,11]
let output = input
  .filter{$0 % 2 == 0}
  .map{String($0)}
  .reduce(""){$0.characters.count == 0 ? $1 : $0 + "," + $1}

print(output)

Teaches:

  • map, filter, reduce
  • chaining

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.


Comments

comments powered by Disqus