如何在 Swift 中获取多行字符串文字的索引

How do I get the index of a multi-line string literal in Swift

我正在尝试查找与指定值匹配的字符串的索引。一种方法是使用实​​例方法,但这假设我正在使用数组;我正在使用多行字符串文字。关于此主题的 documentation 大部分内容涉及 在 Swift 中使用 预定义 值制作 多行字符串文字。

假设我有以下多行字符串文字:

"""
Product 1 description
Product 1 color
Product 2 description
Product 2 color
"""

我想定义两个变量:一个用于检查全局变量是否与上面列表中的字符串匹配,第二个用作索引。例如:

[In]  [1]: let keyword = "Product 2 description"
[In]  [2]: if keyword in multi-line string literal {
              print(index of match as integer)
           }
[Out] [3]: 2

我已经通过使用 Levenshtein distance 计算器查找和定义匹配成功地实现了我程序中的第一个变量,但是我在实现第二个变量时遇到了问题。我试过拆分列表并制作元组,但是当我 enumerated() 遍历列表时,每个字符串都产生了 0 的索引。也就是说,如果有人可以帮助我 任何 以下内容,我将不胜感激:

最简单的解决方案是通过分隔行来创建字符串数组

let string =
"""
Product 1 description
Product 1 color
Product 2 description
Product 2 color
"""

let list = string.components(separatedBy: CharacterSet.newlines)

然后你可以用

得到索引
let indexOfProduct2Description = list.index(of: "Product 2 description")