Last active
July 30, 2023 13:09
-
-
Save stevenschobert/540dd33e828461916c11 to your computer and use it in GitHub Desktop.
Camel-case a string in Swift
This file contains hidden or 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
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") |
This file contains hidden or 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
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 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
@Gatada it's exactly like @MadsBogeskov wrote it.
Pascal Casing = PascalCasing
Camel Casing = camelCasing