Convert camel case to snake case in Swift

This tutorial will see how to convert the camel case to the snake case in Swift.
First of all what are camel and snake cases?
Camel and snake are the two styles of text. In the camel case, the text is written without spaces and punctuation marks in between like “CamelCase”. And in the snake case, the text is in lowercase and every phrase is preceded by an underscore like “snake_case”.

Algorithm

  • Step 1: Import the swift foundation package to use its functionalities in code.
  • Step 2: Declare the function to convert camel case to snake case with the return type of string. Pass the input string as an argument to the function without any label.
  • Step 3: Declare the regular expression pattern for camel string. It represents the sequence of lowercase letters or digits followed by uppercase digits.
  • Step 4: Create the NSRegularExpression instance and pass the regular expression pattern as a pattern to it with an empty options array.
  •  Step 5: Set the NSRange instance with starting location of the string as location and length equal to the count of strings utf16 code units.
  • Step 6: Now check if the string is matching with the regular expression pattern for the camel case string if yes then replace it with the snake case string. stringByReplacingMatches() function is used to do it.
    This function checks if the string matches the regular expression and if yes returns the string by replacing it with a template string.
    Parameters of the function:
    1. in: Input string to check-in.
    2. options: Regular expression options. Equal to an empty array.
    3. range: Equal to NSRange.
    4. withTemplate: It is a template string used to replace when a regular expression matches the string.
  • Step 7: Finally, convert the obtained string into lowercase using lowercased() function. and return it.
  • Step 8: Set some string as input string. Then call the function and pass the input string to the function. Print the result.

Swift Code to convert camel case to snake case

Here is the full swift code to convert the camel case string to snake case string.

import Foundation

func camelCaseToSnakeCase(_ input: String) -> String {
    let pattern = "([a-z0-9])([A-Z])"
    let regex = try! NSRegularExpression(pattern: pattern, options: [])
    let range = NSRange(location: 0, length: input.utf16.count)
    let result = regex.stringByReplacingMatches(in: input, options: [], range: range, withTemplate: "$1_$2")
    return result.lowercased()
}

let input = "camelCaseExample"
let output = camelCaseToSnakeCase(input)
print(output)

Output:

camel_case_example

Also, refer to Convert all characters in the Swift string to uppercase

Leave a Reply

Your email address will not be published. Required fields are marked *