an extension that converts snake case string to camel case string in swift

main.swift
extension String {
    func snakeCaseToCamelCase() -> String {
        let components = self.components(separatedBy: "_")
        let capitalizedComponents = components.map { $0.capitalized }
        let joinedString = capitalizedComponents.joined()
        let firstCharacterLowercased = joinedString.prefix(1).lowercased() + joinedString.dropFirst()
        return firstCharacterLowercased
    }
}

let snakeCase = "my_snake_case_string"
let camelCase = snakeCase.snakeCaseToCamelCase()
print(camelCase) // Output: mySnakeCaseString
535 chars
14 lines

This extension adds a snakeCaseToCamelCase method to String class in Swift. It splits the string into components using underscore as the separator, capitalizes each component, and then joins them together. Finally, it converts the first character to lowercase to match the camel case convention.

related categories

gistlibby LogSnag