0

I am solving a programming problem in Swift and I found a solution online which I don't totally understand, the problem is: Write a function that reverses characters in (possibly nested) parentheses in the input string. the solution is

var inputString = "foo(bar)baz(ga)kjh"

    var s = inputString
    while let openIdx = s.lastIndex(of: "(") {
        let closeIdx = s[openIdx...].firstIndex(of:")")!
        s.replaceSubrange(openIdx...closeIdx, with: s[s.index(after: openIdx)..<closeIdx].reversed())
    }

print (s) // output: foorabbazagkjh (the letters inside the braces are reversed) 

I d like to have details about: lastIndex(of: does in this case and what let closeIdx = s[openIdx...].firstIndex(of:")")! does as well

Rich
  • 115
  • 1
  • 9
  • 1
    The documentation would be a good start: https://developer.apple.com/documentation/swift/string/2997132-lastindex, https://developer.apple.com/documentation/swift/string/2997120-firstindex – Martin R Sep 20 '19 at 10:29
  • Not related to your question but this would crash if it finds an opening bracket unbalanced. Don't force unwrap it `let closeIdx = s[openIdx...].firstIndex(of:")")!` – Leo Dabus Sep 20 '19 at 10:35

1 Answers1

2

The best place to experiment with these kinds of questions would Playground. Also, check out the documentation.

Now let go through each of the statement:

let openIdx = s.lastIndex(of: "(") // it will find the last index of "(", the return type here is Array.Index?

so if I print the value after with index including till end of string, it would be

print(s[openIdx!...]) // `!` exclamation is used for forced casting
// (ga)kjh

Now for your second question;

let closeIdx = s[openIdx...].firstIndex(of:")")!

Let break it down s[openIdx...] is equal to (ga)kjh in first iteration and so it will return the index of ) after a.

The suggestion would be always break the statement and learn what each expression is doing.

Rahul
  • 2,056
  • 1
  • 21
  • 37