Skip to content

Instantly share code, notes, and snippets.

@ivanbruel
Last active March 19, 2023 16:42
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ivanbruel/e72d938f49db64d2f5df09fb9420c1e2 to your computer and use it in GitHub Desktop.
Save ivanbruel/e72d938f49db64d2f5df09fb9420c1e2 to your computer and use it in GitHub Desktop.
Camel case to snake case in Swift
extension String {
func snakeCased() -> String? {
let pattern = "([a-z0-9])([A-Z])"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: self.characters.count)
return regex?.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "$1_$2").lowercased()
}
}
@dmsl1805
Copy link

In case anyone needs it, I updated it for Swift 4.2 version. Thanks!
https://gist.github.com/dmsl1805/ad9a14b127d0409cf9621dc13d237457

@Vadim-Lavrov
Copy link

Thank you.

@andrii-popov-jt
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment