Return several indexes of an array in Swift 4

1

I would like to know how I can get several indexes within an array of strings or characters.

An example:

var arrayInput = ["2","+","3","(","2","-","4","(","3","*","5",")",")",]

func isParentheses() {
    var count = 0
    var arrayNumParentesis:Array<String> = []

    for x in arrayInput {
        if x == "(",
            let index = arrayInput.index(of: x) {
                let y = index
                arrayNumParentesis.append(y)
                print(arrayNumParentesis)

        }
    }
}

I try to enter the values of the position in the array of the parenthesis opening characters but as you can see, only the value of the first one is saved.

Thanks in advance.

    
asked by Jonay B. 12.07.2018 в 21:19
source

1 answer

1

The problem in your code seems to be when you do:

let index = arrayInput.index(of: x)

because it always returns the index of the first parenthesis in the array .

The solution in this case would be to iterate over the indexes and not over the elements of the array :

for i in 0..<arrayInput.count {
    if arrayInput[i] == "(" {
        arrayNumParentesis.append(i)
    }
}
print(arrayNumParentesis)

However, doing so would have to implement it for each value you want to search. The parentheses should be a parameter of your function.

In fact, getting indexes from a list with repeated elements seems to be something that could be applied to any array (as long as its elements are comparable). A more generic solution would be to extend the data type Array . Something like this:

extension Array where Array.Element: Equatable {
    func indexesOf(_ item: Element) -> [Int] {
        var result: [Int] = []
        for i in 0..<self.count {
            if self[i] == item {
                result.append(i)
            }
        }
        return result
    }
}

and then you get the indexes with:

let p = arrayInput.indexesOf("(")
print(p)

The result in your example is:

[3, 7]
    
answered by 12.07.2018 / 21:39
source