【问题标题】:iOS/Swift: why contains doesn't work to detect a substring in the .firstIndex function?iOS/Swift:为什么 contains 不能检测 .firstIndex 函数中的子字符串?
【发布时间】:2021-10-26 18:01:15
【问题描述】:

我正在使用函数 .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

我该怎么办?

【问题讨论】:

  • 你的字符串是从哪里来的?你为什么不创建一个json字符串呢?

标签: arrays swift string substring array-indexing


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2022-12-07
    • 1970-01-01
    • 2020-05-07
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多