Extentions

String+Extensions.swift

Overview

The String+Extensions.swift file in the ShipThatApp application provides a set of utility methods adding functionality to the native String type in Swift. It focuses on extending String to perform common tasks such as validation checks, which are especially useful for handling user input in forms.

Main Extension

Email Validation

One of the main utilities within String+Extensions.swift is validating whether a String instance is formatted correctly as an email address. This functionality is crucial in user authentication flows where accurate email inputs are necessary.

Implementation:

The extension adds a method isValidEmail that uses regular expression pattern matching to determine if the string adheres to a standard email format.

Usage

The isValidEmail method can be called on any String instance to check if it's an email format. For example, when a user inputs their email during sign-up or login, the application can validate the user's input as follows:

if userInput.isValidEmail() {
    // Proceed with valid email address
} else {
    // Show an error message to the user
}

Customization

Developers can add more extensions to String that might be useful across the app. For instance:

  • Extensions for password strength checks.
  • Extensions to format strings, such as phone numbers or currency.
  • Extensions to sanitize strings, removing unwanted characters or white spaces.

Testing

For unit testing String+Extensions, create String instances with known content and test the output of the extension methods. For example:

func testEmailValidation() {
    let validEmail = "test@example.com"
    let invalidEmail = "test_at_example.com"
    XCTAssertTrue(validEmail.isValidEmail(), "The method should return true for a valid email")
    XCTAssertFalse(invalidEmail.isValidEmail(), "The method should return false for an invalid email")
}
Previous
SplashScreenStateManager