Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created October 13, 2020 19:38
Show Gist options
  • Save dfrobison/81c45e67a561309dde3f93ea44cd6a8e to your computer and use it in GitHub Desktop.
Save dfrobison/81c45e67a561309dde3f93ea44cd6a8e to your computer and use it in GitHub Desktop.
//We can also format lists. Suppose you want to say “Apples, eggs, and pears” when you have the following array:
let items = ["apples", "eggs", "pears"]
//You can probably think of a clever way to concatenate the first two items only with a comma and then follow the last item with the word “and”. In fact doing so may not be complicated, but we have ListFormatter which allows us to do just that in just one line of code:
let items = ["apples", "eggs", "pears"]
//ListFormatter.localizedString(byJoining: items) // apples, eggs, and pears
//If you remove one of the elements, the formatter will do the right thing:
let items = ["apples", "pears"]
ListFormatter.localizedString(byJoining: items) // apples and pears
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment