0ndre_ 0ndre_ - 2 months ago 16
Swift Question

UIPickerView select row where title == String in Swift

I have a

UIPickerView
and I would like to select a row where title is equal to String , which I receive from my php/mysql script.

Let's say that this is my Array:

var myArray = ["First","Second","Third","Fourth","Sixth","Seventh"]


And this is what I get from my php script (That's what I want my
UIPickerView
to select.):

let myString = "Second"


So my question is:

How can I do something like this:
self.myPicker.selectRow(1, inComponent: 0, animated: true)
but I want myPicker to select row with title: "Second".

I have found this question but it is in objective-c : UIPickerView Set Selected Row by Title

Thank you very much!

Answer

If you doesn't know the index of your object in array than try like this.

let index = myArray.indexOf(myString)
self.myPicker.selectRow(index, inComponent: 0, animated: true)

If you are working with swift 3 then find index like this.

let index = myArray.index(of: myString)

Edit: If you doesn't sure that your array is contain your string than you can check for nil also.

if let index = myArray.indexOf(myString) {
    self.myPicker.selectRow(index, inComponent: 0, animated: true)
}