OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Letters In Swift

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

When dealing with user input in Swift, it’s important to ensure the input only contains appropriate characters. In this article, we’ll focus on one aspect of this: how to check if a string only contains letters.

Code Snippet: Checking If a String Contains Only Letters

Here is the Swift code snippet you need to implement this check:

import Foundation

func isAlphabetic(s: String) -> Bool {
    return !s.isEmpty && s.rangeOfCharacter(from: CharacterSet.letters.inverted) == nil
}

let str = "Hello"
print(isAlphabetic(s: str))  // Returns: true

You can test this with various strings to see how the function reacts.

Code Explanation: Checking If a String Contains Only Letters

Let’s break this code down into steps to better understand how it works.

  1. We first import the Foundation framework. This is a necessity as it contains the CharacterSet type which we use in this function.

  2. The function isAlphabetic(s: String) is declared. It takes in a string parameter s, and it returns a Boolean value. This function will return true if the string s only contains letters, and false otherwise.

  3. Inside the function body, !s.isEmpty checks if the string is not empty. This is essential because an empty string would technically not contain any characters not in the Character set of letters and it would return true. However, in most practical scenarios, an empty string should not be considered as a string that contains only letters.

  4. s.rangeOfCharacter(from: CharacterSet.letters.inverted) == nil is the main component. CharacterSet.letters.inverted represents a set of all characters that are not letters. s.rangeOfCharacter(from: that_inverted_set) will return nil if there are no such characters in the string s i.e., if string s contains only letters.

  5. We use a test string “Hello” to test our function. When the isAlphabetic function returns true, it indicates that the string only contains letters, as is the case with “Hello”.

That wraps up our look at checking if a string only contains letters in Swift. As you can see, it involves just a short snippet of code but nicely demonstrates some key concepts in character and string handling.

swift