-
-
Save dinneo/6e6ee02bef6abc3d28d70abab0cfaf73 to your computer and use it in GitHub Desktop.
Camel-case a string in Swift
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
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment