0

I'm trying to get the index (i.e. position of the word in the array) of a word in a 2D Array when a button is pressed. The word that I am looking for is the title of the button pressed.

@IBAction func buttonPressed(_ sender: UIButton) {

    let buttonSelected = sender.currentTitle!
    let findIndex = myArray.firstIndex(of: englishButtonSelected)!

}

when I build the code I get this error:

Cannot convert value of type 'String' to expected argument type '[String]'

The constant "buttonSelected" is a String.

I'm new to swift and still learning. Any help is much appreciated! Thank you!

Using Xcode 11.4

PBE_90
  • 1
  • 3
  • Did you write any UIButton extension to get the title of button with `currentTitle`? Where do you declare `myArray`? Sorry, but your code block is not informative enough – Ahmet Sina Ustem Apr 03 '20 at 22:58
  • https://stackoverflow.com/a/47104384/2303865 – Leo Dabus Apr 03 '20 at 23:15
  • 1
    @LeoDabus thank you that was very helpful! I will use those methods for other areas in my code. Looks very effective! – PBE_90 Apr 04 '20 at 21:25

2 Answers2

0

You're almost there. firstIndex will return the first index where a given element appears. Because myArray is a [[String]] (2D Array), it's expecting you to put a [String] in, because each element is a [String]. For example:

let myArray = [["A", "B"], ["C"], ["D", "E"]]
let index = myArray.firstIndex(of: ["D", "E"]) // index = 2

If you want to get the 'absolute' index of the button title (in the example above, this would correspond to the index of "C" being 2, or "E" being 4), you can use:

myArray.flatMap { $0 }.firstIndex(of: buttonTitle)

The .flatMap collapses a 2D array into a regular array. If you want to find the index of the button title within its own sub-array, you'll have to loop through the 2D array and check the index of each sub-array for the button title.

nanothread
  • 908
  • 3
  • 10
  • 25
  • Thank you so much, that makes a lot of sense! I want the output to be something like this "position [0][9]" so how do I loop a search as you suggested? – PBE_90 Apr 03 '20 at 22:14
0

After some googling, I found out how to find the output I'm looking for. This gave me the exact index in [?][?] format of my 2D Array!

for i in 0..<myArray.count {
    for j in 0..<myArray[i].count {
        if myArray[i][j] == buttonSelected {
            print (i, j)
        }
    }
}
PBE_90
  • 1
  • 3
  • Why didn't you look at the linked answer? – Alexander Apr 06 '20 at 13:18
  • @Alexander-ReinstateMonica that link was given after I already found the solution. – PBE_90 Apr 06 '20 at 16:30
  • I would recommend you check it out. Manual indexing, nested loops, etc. are pretty rare in Swift, and not very conventional. Most operations are already baked into the standard library (in this case, finding the first index where a condition is true), so it's conventional to use those. – Alexander Apr 06 '20 at 17:13