Skip to content

Instantly share code, notes, and snippets.

@blixt
Created April 7, 2016 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blixt/3a36f2388509dcd7f41ff5a9010a36dc to your computer and use it in GitHub Desktop.
Save blixt/3a36f2388509dcd7f41ff5a9010a36dc to your computer and use it in GitHub Desktop.
Localized lists in Swift
extension SequenceType where Generator.Element == String {
func localizedJoin() -> String {
var g = self.generate()
guard let first = g.next() else {
return ""
}
guard let second = g.next() else {
return first
}
guard var last = g.next() else {
return String.localizedStringWithFormat(NSLocalizedString("%@ and %@", comment: "List; only two items"), first, second)
}
var middle = second
while let piece = g.next() {
middle = String.localizedStringWithFormat(NSLocalizedString("%@, %@", comment: "List; more than three items, middle items"), middle, last)
last = piece
}
return String.localizedStringWithFormat(
NSLocalizedString("%@, and %@", comment: "List; more than two items, last items"),
String.localizedStringWithFormat(NSLocalizedString("%@, %@", comment: "List; more than two items, first items"), first, middle),
last)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment