Refactor problem 2 in Swift to use functional style