Last active
May 18, 2019 03:13
-
-
Save adamgraham/1b5ebbc949d00b32735eb884e68e9a9a to your computer and use it in GitHub Desktop.
An extension of the Swift String type to provide snake case formatting.
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
/// An extension to format strings in *snake case*. | |
extension String { | |
/// A collection of all the words in the string by separating out any punctuation and spaces. | |
var words: [String] { | |
return components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty } | |
} | |
/// Returns a lowercased copy of the string with punctuation removed and spaces replaced | |
/// by a single underscore, e.g., "the_quick_brown_fox_jumps_over_the_lazy_dog". | |
/// | |
/// *Lower snake case* (or, illustratively, *snake_case*) is also known as *pothole case*. | |
func lowerSnakeCased() -> String { | |
return self.words.map({ $0.lowercased() }).joined(separator: "_") | |
} | |
/// Returns an uppercased copy of the string with punctuation removed and spaces replaced | |
/// by a single underscore, e.g., "THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG". | |
/// | |
/// *Upper snake case* (or, illustratively, *SNAKE_CASE*) is also known as | |
/// *screaming snake case*. | |
func upperSnakeCased() -> String { | |
return self.words.map({ $0.uppercased() }).joined(separator: "_") | |
} | |
/// Returns a copy of the string with punctuation removed and spaces replaced by a single | |
/// underscore, e.g., "The_quick_brown_fox_jumps_over_the_lazy_dog". Upper and lower | |
/// casing is maintained from the original string. | |
func mixedSnakeCased() -> String { | |
return self.words.joined(separator: "_") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment