Skip to content

Instantly share code, notes, and snippets.

@KyLeggiero
Last active September 11, 2018 19:29
Show Gist options
  • Save KyLeggiero/dbe7f2f8845087e46ac94485955abaab to your computer and use it in GitHub Desktop.
Save KyLeggiero/dbe7f2f8845087e46ac94485955abaab to your computer and use it in GitHub Desktop.
Slight tweaks to Cortis Clark's joinedWithComma function
extension Array where Iterator.Element == String {
/// Originally by Cortis Clark on StackOverflow, modified by Ben Leggiero for an example
/// - SeeAlso: https://stackoverflow.com/a/52266604/3939277
func joinedWithComma(useOxfordComma: Bool = true, maxItemCount: UInt8? = nil) -> String {
let result: String
if let maxItemCount = maxItemCount, count > maxItemCount {
result = self[0 ..< maxItemCount].joined(separator: ", ") + ", etc."
} else if count >= 2 {
let lastIndex = count - 1
let extraComma = (useOxfordComma && count > 2) ? "," : ""
result = self[0 ..< lastIndex].joined(separator: ", ") + extraComma + " and " + self[lastIndex]
} else if count == 1 {
result = self[0]
} else {
result = ""
}
return result
}
}
// Usage example:
let numbers = [1, 2, 3, 4]
print(numbers.joinedWithComma()) // Default; prints "1, 2, 3, and 4"
print(numbers.joinedWithComma(maxItemCount: 2)) // A maximum of 2 items; prints "1, 2, etc."
print(numbers.joinedWithComma(maxItemCount: 2)) // A maximum of 10 items; prints "1, 2, 3, and 4"
print(numbers.joinedWithComma(maxItemCount: nil)) // No maximum of items; prints "1, 2, 3, 4"
print(numbers.joinedWithComma(maxItemCount: -1)) // Unclear; fails to compile
@KyLeggiero
Copy link
Author

Original answer by Cortis Clark on StackOverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment