Search code examples
arraysswifttuplesuipickerview

UIPicker from Array of Tuples


How can I load a UIPickerView with an array of tuples?

With the following code I only see Oregon: 9.0 in the UIPickerView.

let myArrayTuple: [(String, Double)] = [("Illinois", 7.0), ("Wisconsin", 8.0), ("Oregon" ,9.0)]

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    
    var stateName:String?
    var stateTax:Double?

    for (name , tax) in myArrayTuple{
         stateName = name
         stateTax = tax
    }
    return stateName! +  ": \(stateTax!)"
}

EDIT: Here is how you do it: See answer from Shadow Of

In my example below I'm using named tuples instead of the defaults as in Shadow Ofs example.

let myArrayTuple: [(name:String, tax:Double)] = [("Illinois", 7.0), ("Wisconsin", 8.0), ("Oregon" ,9.0)]

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    

    let stateName = myArrayTuple[row]
    return stateName.name +  ": \(stateName.tax)"
}

Solution

  • Thats how you should work with your UIPickerView, I guess:

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return myArrayTuple.count
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let current = myArrayTuple[row]
        return current.0 + ": \(current.1)"
    }