Search code examples
arraysswiftstringsubstringarray-indexing

iOS/Swift: why contains doesn't work to detect a substring in the .firstIndex function?


I am using the function .firstIndex to locate a specific substring in an array of arrays. But when I put the entire string, it works, but if I put only a substring of that string, this doesn't work.

enter image description here

let index = programArray.firstIndex(where: {$0.contains("2021-14-09")}) //Index is nil => bad
let index = programArray.firstIndex(where: {$0.contains("2021-14-09 08:00:00")}) // Index is 0 => good

If i use it not in the firstIndex function it works, it is strange...

let test = "2021-14-09 08:00:00"
let test2 = test.prefix(10).contains("2021-14-09") // true => good

How can I do?


Solution

  • You use contains(_:), but if you look into the Apple Developer Documentation you see:

    Returns a Boolean value indicating whether the sequence contains the given element.

    So the whole string has to match if you use contains.