Count Dictionary Entries in Plist Swift Xcode

Hey everyone,

I was wondering if I could ask for some help?

I am currently learning about NSArrays and NSDictionaries. I’m trying to make a pickerview with the number of NSDictionaries in my plist (below)

.

So far my code can count the amount of arrays in the plist (1), but I can’t count the dictionaries. Does anyone know how I would go about this? I want to get the picker view to show from 1-(dictionary count (32 in this case))

So far my code is as follows:

In the Quiz Controller (this is the controller that allows me to communicate between the category selection view and the picker view.

struct Quiz {

private(set) var name = String()
private(set) var plist: [[NSDictionary]]!



init(name: String) {
	self.name = name
	plist = NSArray(contentsOfFile: Bundle.main.path(forResource: name, ofType: "plist")!)! as! [[NSDictionary]]
 
    
     
   
}

static let quizzes = [Quiz(name: "Development"), Quiz(name: "Reflexes")]

}

In the picker view controller:

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Quiz.quizzes[currentTopicIndex].plist.count
}

I would appreciate any help you guys could give on the matter.

I couldn’t figure this out, so I just got rid of the item 0 as an array and just had root as an array and the rest as dictionaries and it worked :slight_smile:

@kailas198. I’m glad you were able to solve the problem on your own, and I apologize for not being able to get to your question sooner.

All the best!

1 Like

You shouldn’t use NSDictionary or NSArray in your swift code. If you need to read your plist, do it like so:

let url = Bundle.main.url(forResource: “filename”, withExtension: “plist”)!
let data = try! Data(contentsOf: url)
let plist = try! PropertyListSerialization.propertyList(from: data, options: , format: nil) as! [[[String : Any]]]

Now “plist” is an array of array of dictionary entries, where the key is a string and the value is Any type. Based on your pictures you’ve got a plist which is array based. Each element of that array is ALSO an array. And then the elements of that inner array are the dictionaries. That’s why I used three open brackets and not two in the cast.

So what you are really asking is to take the first element of the array, and then take that things first element, and then count the elements in that. So you end up with

let allItems = plist[0]
for item in allItems {
// Process each individual dictionary element here.
}

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.