Search code examples
swiftswift4

Enumerate String from specific index in nested loop in Swift


To get characters from String using enumerated() method

let str = "Hello"

for (i,val) in str.enumerated() {
        print("\(i) -> \(val)")
}

now trying to enumerate same string inside for loop but from i position like

for (i,val) in str.enumerated() {
        print("\(i) -> \(val)")
        for (j,val2) in str.enumerated() {
            // val2 should be from i postion instead starting from zero
        }
}

How to enumerate and set j position should start from i?

Thanks


Solution

  • You can use dropFirst() to create a view in the string starting with a specific position:

    for (i,val) in str.enumerated() {
        print("i: \(i) -> \(val)")
        for (j, val2) in str.dropFirst(i).enumerated() {
            print("j: \(i+j) -> \(val2)")
        }
    }
    

    You need to add i in the second loop if you want to get the index corresponding to the original string, otherwise j will hold the index in the view created by dropFirst()