Last active
December 17, 2019 17:50
-
-
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.
This file contains 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
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)" | |
} | |
} |
This file contains 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
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