Search code examples
arraysswiftuipickerview

Looping through an array to get index of item - swift


I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.

I have the following code however this causes the app to crash due:

let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
        scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)

When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.

Any ideas on why this may be happening?

Using the suggested answer throws the following error:

unrecognized selector sent to instance 0x101134af0'

There is definitely a match in assetArray[0] with the name that is being passed through.

Doing a bit more investigation trying to run the following line of code alone gives the same error:

scroll_owners.selectRow(0, inComponent: 0, animated: true)

Does this mean I'm missing a delegate method?

Asset Array and Name Array:

var assetArray : [Asset] = []

var nameArray = [String]()

EDIT:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
}

    self.scroll_owners.delegate = self
    self.scroll_owners.dataSource = self

I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:

            var i : Int = 0
        while (nameArray[i] != name)
        {
            print(nameArray[i])
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: 0, animated: true)

This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?


Solution

  • I have managed to solve this error myself in a slightly different way.

    In my function which populates the nameArray and the UIPicker I have placed the following code:

                    var i : Int = 0
                while (self.nameArray[i] != name)
                {
                    print(self.nameArray[i])
                    i=i+1
                }
                self.scroll_owners.selectRow(i, inComponent: 0, animated: true)
    

    The reason the code was crashing was due to the fact that the nameArray was not finishing being populated before I was trying to do the comparisons. I know this may not be the accepted swift way of doing this but it works.

    The issues were caused due to the function being run on a seperate thread I believe.