Swift String Class Utilities and Cheat Sheet

Swift String class is the most important class of Foundation framework,  Stringclass is being widely used throughout the projects. If a string is so much popular then, should we have utility class of this?  The answer is you must have. It will speed up your development time for sure. So let’s begin…
First, create a swift file and name String+Additions.swift In this file create an extension of String class, after this, your file will look like this. The extension is a great way to add functions in the class without inherite its superclass. You can call these functions from any class throughout the project with the object of String class.


import Foundation

extension String {

}

Now let’s start adding functions…

HTML to Plain Text

Sometimes we get HTML string from API or any other sources, and we have to display only plain text. Let’s add below function in String-extension


func htmlToPlainText() ->String {
    
    if let data = self.data(using: .utf8) {
        do {
            let htmlAttributedString = try NSAttributedString(data: data, options: [.documentType:
				NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
				documentAttributes: nil)
            return htmlAttributedString.string
        } catch {
            print("error:", error)
            return ""
        }
    }
    return ""
}

In the above function first, we created Data from the string, then convert this data into NSAttributedString. Now NSAttributedString class has a var string which returns the plain text. Now let’s call this functions from your class.


let htmlString = "Some html string"// 1        
let plainText = htmlString.htmlToPlainText()// 2        
print("plain text is: \(plainText)")// 3

1. We have a HTML string having HTML tags HTML properties. 2. we are calling  htmlToPlainText() function of string extension, which returns a plain text. 3. Now print this objectplainText and you will get a plain text extracted from HTML string.

Remove Spaces and New Lines

If any string is having new lines or spaces then, use below functions to remove them.


func trimSpace() -> String {
    return self.trimmingCharacters(in: NSCharacterSet.whitespaces)
}

func trim() -> String {
    let trimmedString = self.trimmingCharacters(
        in: CharacterSet.whitespacesAndNewlines
    )
    return trimmedString
}

Here we create a NSCharacterSet of whitespaces and whitespacesAndNewlines, and we simply remove these characterSet from the string.

Check valid Email and Phone Number

Add below functions in your string extension.


func isValidEmail() -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailRegex)
    return emailPredicate.evaluate(with: self)
}

func isValidPhone() -> Bool {
    let phoneRegex = "^[0-9]{8,14}$"
    let phonePredicate = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
    return phonePredicate.evaluate(with: self)
}

Here we use Regex to verify valid email and phone number. We will discuss later in some other post.

Check String is having Numbers

Sometimes we need to check whether a string is having a number or not. To check this add below function in String extension class.


func containsNumbers() -> Bool {
    let charSet = CharacterSet.decimalDigits
    let range = self.rangeOfCharacter(from: charSet)
    if let _ = range {
        return false
    } else {
        return true
    }
}

Here we simply create CharacterSet of decimal and check if, it’s range exist in string or not. If range exists it means the string is having number and code will return true.

Check Emoji String

Sometimes a case may appear where you need to check that your string is an emoji or not. In order to check this add below function in string extension class.


func isEmoji() -> Bool {
    for uitf16Item in self.utf16 {
        if UTF16.isLeadSurrogate(uitf16Item) || UTF16.isTrailSurrogate(uitf16Item) {
            return true
        }
    }
    return false
}

Using this function you can check whether your string is an emoji or not.

NSLocalizedString

Writing NSLocalizedString everywhere is to localize your string doesn’t look good, instead of doing this let’s add below function in string extension class.


func localize() -> String {
    return NSLocalizedString(self, comment: "")
}

The above function will simplify your code in a very impressive way. Let’s see how it look.


myLabel.text = NSLocalizedString("Hello", comment: "") // 1
myLabel.text = "Hello".localize() // 2

1. This is a basic way to localize a string. 2.This is a new way to localize string using a function.

Leave a Reply

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