Chanchal Raj
Chanchal Raj

Reputation: 4316

Comparing string with Optional to non Optional string

Are they both equal strings?

enter image description here

I tried printing them, following is the response:

enter image description here

When tried comparing them, it turns out to be false

enter image description here

I cannot understand, though they both letters are same in Arabic, but still it says, they aren't!

Here is a more contextual picture of what's happening:

enter image description here

Upvotes: 0

Views: 1865

Answers (2)

vadian
vadian

Reputation: 285064

It depends:


This is a non-optional i

let a = "i" // "i"

This is an optional i

let b : String? = "i" // "i"

a and b are equal

a == b // true

However this is an optional i created with String Interpolation

let c = "\(b)" // "Optional("i")"

Now a and c are not equal

a == c // false

This comparation is false because String Interpolation adds literal Optional to the string.

Upvotes: 3

Chanchal Raj
Chanchal Raj

Reputation: 4316

As per CRD's comment, the Optional was misleading. It turned out that the seemingly type Optional was actually an String. Here is how I changed the code to compare the first letters:

for song in allSongs{
   let firstLetter = song.name?.characters.first
   var index = 0
   for letter in sectionTitles{
       if(letter.characters.first == firstLetter){
           break;
       }
       index += 1
   }
   var array = sectionedSongs[index]
   array.append(song)
}

Note sectionedSongs is just an array of arrays.

Upvotes: 0

Related Questions