Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Get the Number of Keys In a Dictionary

Tags:

ios

swift

For swift arrays, we can simply use the count property to find out how many elements are in the collection. However, we can't do the same for dictionary keys. Is the only way to do this to use a for loop and counter?

var myDict:  [String: AnyObject] = // ... intialize dictionary with keys and values  myDict.keys.count // doesn't work 
like image 597
blee908 Avatar asked Sep 02 '14 23:09

blee908


People also ask

How do you check if key already exists in dictionary Swift?

Swift Dictionary contains() The contains() method checks whether the specified key or value is present in the dictionary or not.

Which type is defined for key in dictionary in Swift?

The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ). var emptyDict: [String: String] = [:]

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.

What is key in Swift?

Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.


2 Answers

There is a count property on dictionary, so myDict.count will work.

like image 156
Shan Avatar answered Sep 28 '22 02:09

Shan


Why not simply use the count property on myDict?

myDict.count 

enter image description here

like image 22
Mike Avatar answered Sep 28 '22 04:09

Mike