Skip to content

Instantly share code, notes, and snippets.

@reitzig
Created February 22, 2018 17:26
Show Gist options
  • Save reitzig/67b41e75176ddfd432cb09392a270218 to your computer and use it in GitHub Desktop.
Save reitzig/67b41e75176ddfd432cb09392a270218 to your computer and use it in GitHub Desktop.
Convert Swift strings to camel case
fileprivate let badChars = CharacterSet.alphanumerics.inverted
extension String {
var uppercasingFirst: String {
return prefix(1).uppercased() + dropFirst()
}
var lowercasingFirst: String {
return prefix(1).lowercased() + dropFirst()
}
var camelized: String {
guard !isEmpty else {
return ""
}
let parts = self.components(separatedBy: badChars)
let first = String(describing: parts.first!).lowercasingFirst
let rest = parts.dropFirst().map({String($0).uppercasingFirst})
return ([first] + rest).joined(separator: "")
}
}
@artemstepanenko
Copy link

Great work, thanks for sharing! I think the computation could be even faster if you move uppercasingFirst and lowercasingFirst into an extension of Substring. (There wouldn't even be a need to change their implementations.) Cheers.

@sukhrobkhakimov
Copy link

A more compact version.

extension String {
    var lowercasingFirst: String { prefix(1).lowercased() + dropFirst() }
    var uppercasingFirst: String { prefix(1).uppercased() + dropFirst() }

    var camelCased: String {
        guard !isEmpty else { return "" }
        let parts = components(separatedBy: .alphanumerics.inverted)
        let first = parts.first!.lowercasingFirst
        let rest = parts.dropFirst().map { $0.uppercasingFirst }

        return ([first] + rest).joined()
    }
}

@sidiiq
Copy link

sidiiq commented Nov 16, 2022

how did you come up with this? i am learning swift a while now and i am not gaining much knowledge.

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