首页 > 解决方案 > iOS/Swift:为什么 contains 不能检测 .firstIndex 函数中的子字符串?

问题描述

我正在使用函数 .firstIndex 来定位数组数组中的特定子字符串。但是当我放置整个字符串时,它可以工作,但是如果我只放置该字符串的一个子字符串,这将不起作用。

在此处输入图像描述

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

如果我不在 firstIndex 函数中使用它,它会起作用,这很奇怪......

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

我能怎么做?

标签: arraysswiftstringsubstringarray-indexing

解决方案


您使用 contains(_:),但如果您查看Apple Developer Documentation,您会看到:

返回一个布尔值,指示序列是否包含给定元素。

所以如果你使用包含,整个字符串必须匹配。


推荐阅读