Search code examples
swiftmacoscocoaswift4multiline

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


I'm trying to find the index of a string that matches a specified value. One way to do this would be to use an instance method, but this assumes I'm working with an array; I'm working with a multi-line string literal. Much of the documentation on this topic concerns making multi-line string literals in Swift with pre-defined values.

Let's say I have the following multi-line string literal:

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

I'd like to define two variables: one to check if a global variable matches a string in the list above, and a second to act as the index. For example:

[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

I've managed to fulfil the first variable in my program by using the Levenshtein distance calculator to find and define a match, but I'm having trouble fulfilling the second one. I've tried splitting the list and making tuples, but each string yielded an index of 0 when I enumerated() over the list. That said, if anyone could help me with any the following, I would much appreciate the help:

  • Getting index values of the above multi-line string literal
  • Defining a count variable whose value is an integer that changes over each string iteration
  • Turning the above multi-line string literal into a list whereby each string has an index

Solution

  • The simplest solution is to create an array of the string by separating the lines

    let string =
    """
    Product 1 description
    Product 1 color
    Product 2 description
    Product 2 color
    """
    
    let list = string.components(separatedBy: CharacterSet.newlines)
    

    Then you can get the index with

    let indexOfProduct2Description = list.index(of: "Product 2 description")