Last active
March 30, 2018 03:39
-
-
Save AmitaiB/5903e1316f57151666c392468446d27c to your computer and use it in GitHub Desktop.
Turns CamelCase and lamaCase strings into snakecase aka underscorecase (Swift 3.0)
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
// 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