Peter Burgundy
Peter Burgundy

Reputation: 81

NSArray to populate uiPickerView

I have the following NSArray:

rollupList =
[
    {"id":"1","rollup":"Acme Servicing","o_offered":"9780"},
    {"id":"2","rollup":"Acme Sales","o_offered":"4512"},
    ...
]

I'm trying to extract all "rollup" to display them in a uiPickerView without any success.

I'm able to get the "rollup" value when I enter the index

let rowLOALogs: NSDictionary = self.rollupList[0] as! NSDictionary
print((rowLOALogs["rollup"] as? String)!) //result: Acme Servicing

But I'm getting all kinds of errors when populating the uiPickerView:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return self.rollupList[row]
    //or return self.rollupList[row].rollup
    //or return return (self.kpiData[row] as AnyObject).rollup
}

I've been searching and testing different solutions provided by SO but I can't seem to get it to work.

Any help would be appreciated

Upvotes: 0

Views: 231

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to return String from titleForRow method same way you are printing rollup from the array. So it should be like.

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let rowLOALogs = self.rollupList[row] as! NSDictionary
    return rowLOALogs["rollup"] as? String
}

Note: In Swift instead of using NSArray and NSDictionary you need to use Swift's native Array and Dictionary that will make things a lot easier to understand, even if you use Array of custom class objects or struct then it makes to easy to do what you want.

Upvotes: 1

Related Questions