Last active
September 11, 2018 19:29
-
-
Save KyNorthstar/dbe7f2f8845087e46ac94485955abaab to your computer and use it in GitHub Desktop.
Slight tweaks to Cortis Clark's joinedWithComma function
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original answer by Cortis Clark on StackOverflow