a swift extension that converts camel case to snake case in swift

You can create a Swift extension on the String type to convert a string from camel case to snake case. Here's an example implementation:

main.swift
extension String {
    func camelCaseToSnakeCase() -> String {
        let input = self
        
        guard input.count > 0 else {
            return input
        }
        
        var snakeCase = ""
        var currentIndex = input.startIndex
        
        while currentIndex < input.endIndex {
            let currentChar = input[currentIndex]
            
            if currentChar.isUppercase {
                if currentIndex != input.startIndex {
                    snakeCase.append("_")
                }
                snakeCase.append(Character(currentChar.lowercased()))
            } else {
                snakeCase.append(currentChar)
            }
            
            currentIndex = input.index(after: currentIndex)
        }
        
        return snakeCase
    }
}
798 chars
30 lines

You can use this extension on any String object to convert it from camel case to snake case, like this:

main.swift
let camelCaseString = "thisIsACamelCaseString"
let snakeCaseString = camelCaseString.camelCaseToSnakeCase()
print(snakeCaseString) // Output: this_is_a_camel_case_string
170 chars
4 lines

This extension iterates through each character in the input string and checks if it is an uppercase character. If it is, it appends an underscore followed by the lowercase version of the character to the snake case string. If the character is not uppercase, it simply appends it to the snake case string.

gistlibby LogSnag