Rich
Rich

Reputation: 125

Explanation of lastIndex of: and firstIndex of: used in a string in Swift

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

Upvotes: 0

Views: 667

Answers (1)

Rahul
Rahul

Reputation: 2100

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.

Upvotes: 2

Related Questions