Skip to content

Instantly share code, notes, and snippets.

@zef
Last active December 17, 2019 17:50
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 zef/49000f7807a1f94cf0c0d85b478ef4ca to your computer and use it in GitHub Desktop.
Save zef/49000f7807a1f94cf0c0d85b478ef4ca to your computer and use it in GitHub Desktop.
A simple protocol to enable a collection of Pluralizable objects to return either the singular or the plural, depending on the count of the collection.
protocol Pluralizable {
static var singular: String { get }
// Override with the correct plural, if simply appending an "s" is incorrect
static var plural: String { get }
}
extension Pluralizable {
static var singular: String {
return String(describing: self)
}
static var plural: String {
return "\(singular)s"
}
}
extension Collection where Element: Pluralizable {
var pluralize: String {
return count == 1 ? Element.singular : Element.plural
}
var pluralizeCount: String {
return "\(count) \(pluralize)"
}
}
struct Capital {}
extension Capital: Pluralizable {}
[Capital]().pluralize // "Capitals"
[Capital()].pluralize // "Capital"
[Capital(), Capital()].pluralize // ""Capitals
struct Country {}
extension Country: Pluralizable {
static var plural: String {
return "Countries"
}
}
[Country]().pluralizeCount // "0 Countries"
[Country()].pluralizeCount // "1 Country"
[Country(), Country()].pluralizeCount // "2 Countries"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment