Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Last active March 30, 2018 03:39
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 AmitaiB/5903e1316f57151666c392468446d27c to your computer and use it in GitHub Desktop.
Save AmitaiB/5903e1316f57151666c392468446d27c to your computer and use it in GitHub Desktop.
Turns CamelCase and lamaCase strings into snakecase aka underscorecase (Swift 3.0)
// Swift 3.0
// snake_cased
import Foundation
extension String {
mutating func snake_cased() {
self = self.snake_case()
}
func snake_case() -> String {
var result = ""
var previousCharWasCapitalized = false
for (index, char) in self.characters.enumerated() {
var charStr = String(char)
// remove (ignore) non-alphas
if !charStr.isAlpha { continue }
// If capital is found...
if charStr == charStr.uppercased()
{
// ...lower case it...
charStr = charStr.lowercased()
// If it's not the first letter, nor follows another lowercased letter, prepend an underscore
// (If it followed another operated-on letter, we'd get "JSON" -> "j_s_o_n" instead of "json")
if
index != 0,
!previousCharWasCapitalized {
charStr = "_" + charStr
}
previousCharWasCapitalized = true
}
// If capital is not found, mark it for the next cycle, and move on.
else { previousCharWasCapitalized = false }
result += charStr
}
return result
}
var isAlpha: Bool {
let alphaSet = CharacterSet.uppercaseLetters.union(.lowercaseLetters).union(.whitespacesAndNewlines)
return self.rangeOfCharacter(from: alphaSet.inverted) == nil
}
}
var testString = "authorizationCode"
assert(testString.snake_case() == "authorization_code")
testString.snake_cased()
assert(testString == "authorization_code")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment