Skip to content

Instantly share code, notes, and snippets.

@dinneo
Forked from stevenschobert/camel_case.swift
Created July 30, 2023 13:09
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 dinneo/6e6ee02bef6abc3d28d70abab0cfaf73 to your computer and use it in GitHub Desktop.
Save dinneo/6e6ee02bef6abc3d28d70abab0cfaf73 to your computer and use it in GitHub Desktop.
Camel-case a string in Swift
func camelCaseString(source: String) -> String {
if contains(source, " ") {
let first = source.substringToIndex(advance(source.startIndex, 1))
let cammel = NSString(format: "%@", (source as NSString).capitalizedString.stringByReplacingOccurrencesOfString(" ", withString: "", options: nil, range: nil)) as String
let rest = dropFirst(cammel)
return "\(first)\(rest)"
} else {
let first = (source as NSString).lowercaseString.substringToIndex(advance(source.startIndex, 1))
let rest = dropFirst(source)
return "\(first)\(rest)"
}
}
camelCaseString("os version")
camelCaseString("HelloWorld")
camelCaseString("someword With Characters")
extension String {
var camelCasedString: String {
let source = self
if contains(source, " ") {
let first = source.substringToIndex(advance(source.startIndex, 1))
let cammel = NSString(format: "%@", (source as NSString).capitalizedString.stringByReplacingOccurrencesOfString(" ", withString: "", options: nil, range: nil)) as String
let rest = dropFirst(cammel)
return "\(first)\(rest)"
} else {
let first = (source as NSString).lowercaseString.substringToIndex(advance(source.startIndex, 1))
let rest = dropFirst(source)
return "\(first)\(rest)"
}
}
}
"os version".camelCasedString
"HelloWorld".camelCasedString
"someword With Characters".camelCasedString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment