Compare if two Strings are equal

The two code snippets below are examples of how to compare if two Strings are equal.

Check if two Strings are equal using elementsEqual()

Let’s assume the two Strings are constants and we need to compare them:

let password = "HelloWorld"
let repeatPassword = "HelloWorld"

if ((password.elementsEqual(repeatPassword)) == true)
{
   print("Passwords are equal")
} else {
   print("Passwords are not equal")
}

Compare Text in Two UITextFields

The below code snippet compares if two Strings read from a UITextField are equal. Let’s assume we have two UITextFields:

  • userPasswordTextField
  • and repeatPasswordTextField
// Compare if provided passwords are equal
       
if ((userPasswordTextField.text?.elementsEqual(repeatPasswordTextField.text!))! != true)
{
   // Passwords do not match. Display alert message and return
    return
}

Compare two Strings using caseInsensitiveCompare()

The code snippet below performs case insensitive comparison of two Strings in Swift:

let valueExpected = "SUCCESS"
let valueProvided = "success"

if valueExpected.caseInsensitiveCompare(valueProvided) == ComparisonResult.orderedSame
{
    print("Strings are equal")
}

Checkout the below books and video courses on Mobile Apps Development for iOS Platform which might help you build your dream app sooner :).


 

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon