Created
April 7, 2016 22:40
-
-
Save blixt/3a36f2388509dcd7f41ff5a9010a36dc to your computer and use it in GitHub Desktop.
Localized lists in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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