OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In Swift

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In Swift with sample and detail explanation

Swift is a powerful programming language that offers numerous built-in functions for strings, making it easier for developers to manipulate them. One common task is to check if a string contains only alphanumeric characters. In this article, we are going to check out how you can achieve this in Swift.

Code snippet for Checking Alphanumeric Characters in Swift

In Swift, you can use the following code snippet to test if a string contains only alphanumeric characters - letters and digits.

import Foundation

func isAlphanumeric(testString: String) -> Bool {
    return testString.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}

let myString = "abc123"
if isAlphanumeric(testString: myString) {
    print("\(myString) contains only alphanumeric characters.")
} else {
    print("\(myString) contains non-alphanumeric characters.")
}

Code Explanation for Checking Alphanumeric Characters in Swift

The above Swift code uses a simple approach to check if a string only contains alphanumeric characters.

  1. Firstly, we import the Foundation framework to provide the necessary classes, services, and functions we need.

  2. Then we define a function named isAlphanumeric. This function takes a string, testString, as input.

  3. In the body of the isAlphanumeric function, we are using the range(of:options:) method to find the specified pattern in the string.

  4. The pattern "[^a-zA-Z0-9]" is a regular expression that matches any character that is not a letter or a digit. The ^ sign at the beginning of the pattern denotes negation.

  5. If the method finds a match, it returns the range of the first match. If it doesn’t find any match (which means that the string only contains alphanumeric characters), it returns nil.

  6. Therefore, if the range result is equal to nil, the function isAlphanumeric returns true. Otherwise, it returns false.

In the last portion of the code, we declare a string, myString, test it using the isAlphanumeric function, and then print the results accordingly. So this effectively checks if the string contains only alphanumeric characters.

swift