Skip to content

Instantly share code, notes, and snippets.

@Mreyna3
Last active December 22, 2019 10:38
Show Gist options
  • Save Mreyna3/a50e387487e07218133f89af9fcb3853 to your computer and use it in GitHub Desktop.
Save Mreyna3/a50e387487e07218133f89af9fcb3853 to your computer and use it in GitHub Desktop.
This gist iterates over a collection in a functional fashion using the reduce method to create character delimited String.
struct Person {
let firstName: String
let lastName: String
}
let persons = [Person(firstName: "Eric", lastName: "Franz"),
Person(firstName: "Dwayne", lastName: "Carter"),
Person(firstName: "John", lastName: "Lucas")]
persons.reduce("") { $0 == "" ? $1.name : $0 + "," + $1.name }
//If Xcode complains about not being able to infer generics use the expanded closure notation
//persons.reduce("", {(result:String, item: ConfirmedTransaction) in
// return result == "" ? item.name : result + "," + item.name
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment