Swift - Data Type String Equality

Introduction

In Swift, string and character comparisons are performed using the equal to operator ( == ) or the not equal to operator ( != ).

Two strings are equal if they contain exactly the same Unicode scalars in the same order.

Here is an example:

Demo

var string1 = "I am a string!"
var string2 = "I am a string !"
print(string1 == string2)  //true
print(string1 != string2)  //false

Result

The following example shows a comparison between two Character variables, each containing a Unicode character:

Demo

var s1 = "e"       
var s2 = "\u{E9}"  
print(s1 == s2)

Result

The next example shows a comparison between two String variables:

Demo

var s3 = "cafe"      
var s4 = "caf\u{E9}" 
print(s3 == s4)    //from w w  w.j a v  a  2 s.c o m

let s7 = "\u{E0}"             
let s8 = "\u{61}\u{300}"      
print(s7 == s8)

Result

Related Topic