-
-
Save nerdsupremacist/8e620beb2dcf6404f9edcac756ed28dc to your computer and use it in GitHub Desktop.
Convert Swift strings to camel case
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
fileprivate let badChars = CharacterSet.alphanumerics.inverted | |
extension String { | |
var uppercasingFirst: String { | |
return prefix(1).uppercased() + dropFirst().lowercased() | |
} | |
var lowercasingFirst: String { | |
return prefix(1).lowercased() + dropFirst().lowercased() | |
} | |
var camelized: String { | |
guard !isEmpty else { | |
return "" | |
} | |
guard uppercased() != self else { return lowercased() } | |
let parts = self.parts | |
let first = String(describing: parts.first!).lowercasingFirst | |
let rest = parts.dropFirst().map({String($0).uppercasingFirst}) | |
return ([first] + rest).joined(separator: "") | |
} | |
var upperCamelized: String { | |
guard !isEmpty else { | |
return "" | |
} | |
return parts.map { String($0).uppercasingFirst }.joined(separator: "") | |
} | |
private var parts: [String] { | |
let basics = replacingOccurrences(of: "([a-z])([A-Z])", | |
with: "$1 $2", | |
options: .regularExpression) | |
let complete = basics.replacingOccurrences(of: "([A-Z]+)([A-Z][a-z]|$)", | |
with: "$1 $2", | |
options: .regularExpression) | |
return complete.components(separatedBy: badChars) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment