Search code examples
arraysswiftuipickerview

How do I set a picker title to use a variable float as the initial value? (Swift)


In Swift, I'm trying to set up a picker, such that it will use a returned value as the initial title for row. I know how to set the initial title to a constant place in the array:

class DiagnosticLensVC : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

let myFloatArray : [Float] = [40,40.25,40.5,40.75,41,41.25,41.5,41.75,42,42.25,42.5,42.75,43,43.25,43.5,43.75,44,44.25,44.5,44.75,45,45.25,45.5,45.75,46,46.25,46.5,46.75,47,47.25,47.5,47.75,48,48.25,48.5,48.75,49,49.25,49.5,49.75,50]

// picker view stuff

func viewDidLoad() {
    super.viewDidLoad()

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

  }
}

But how would I set the initial row to a value that is returned from a function? Is there a way to use a dictionary array [Int : Float], and then set keys to number the array, and values to the floats I need to use for calculations, and then set the keys to index the array? Can someone point me in the right direction here?


Solution

  • Not sure if I understand your question correctly:

    You have a function which returns a float and now you want to set the pickerView to that entry in your data array which equals that value?

    Comparing floats with fixed values is usually a bad idea and will drive you nuts. If the result value of your function is surely one of the array values it is probably much better to return the array index instead of a float value based on some computations.

    To find the index for an element in the array:

    if let index = find(myFloatArray,42.75) {
        println(index)   // prints 11
        myPicker.selectRow(index, inComponent: 0, animated: true) 
    }