Skip to content

Instantly share code, notes, and snippets.

@stevenschobert
Last active July 30, 2023 13:09
Show Gist options
  • Save stevenschobert/540dd33e828461916c11 to your computer and use it in GitHub Desktop.
Save stevenschobert/540dd33e828461916c11 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
@Gatada
Copy link

Gatada commented Oct 13, 2021

@Gatada it's exactly like @MadsBogeskov wrote it.
Pascal Casing = PascalCasing
Camel Casing = camelCasing

Hehe, yeah, in retrospect I see how my reply was confusing. I was referring to the method name, not the formatting.

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