String array reduce

Your reduce closure should probably look like this:

var jointGenres : String = genres.reduce("", combine: { $0 == "" ? $1 : $0 + "," + $1 })

This has the "" instead of 0 like you had, and makes sure that there is no extra comma in the beginning of the return value.

The original code did not work because the return type that is represented as U in documentation was originally 0 in your answer, while you are trying to add a String to it. In your case, you really want both U and T to represent Strings instead of Ints.


reduce is not a straightforward solution here since you need special handling for the first element. String's join method is better for this purpose:

let strings = ["a", "b", "c"]
let joinedString = ",".join(strings)

If you know the array is not empty there is another possible solution with reduce that also avoids conditionals:

let joinedStrings = strings[1..<strings.count].reduce(strings[0]) { $0 + "," + $1 }

Tags:

Swift

Reduce