0

I have this simple code :

var dic = [25:"first" , 35 : "second"  , 55 : "third"]
let firstKey = Array(dic.keys)[0] // or .first
print (firstKey)

I guess it suppose to return 25 because the first key at the first index of the dictionary if 25 .But strangely it's returning 35 .

What's wrong ?

Thanks

sali
  • 179
  • 1
  • 12
  • 5
    It's normal, it is not an ordered set of datas.http://stackoverflow.com/questions/1295459/are-keys-and-values-in-an-nsdictionary-ordered – Luca D'Alberti Dec 22 '15 at 08:25
  • 2
    Dictionaries are unordered key-value representation. So it is normal not to print first value of the dictionary. – ridvankucuk Dec 22 '15 at 08:27
  • What do you want to achieve . you first know the basic difference between the dictionary and array and ordered dic – Arun Dec 22 '15 at 08:40

3 Answers3

0

Try

let firstKey = Array(dic.keys).sort()[0]
Jauzee
  • 120
  • 2
  • 18
0

From Swift Doc:

Dictionary

A hash-based mapping from Key to Value instances. Also a collection of key-value pairs with no defined ordering

So by creating a Dictionary with a dictionary literal it is very likely that the ordering is not the same.

Qbyte
  • 12,753
  • 4
  • 41
  • 57
0

You seem to have an assumption that a dictionary is ordered, it is not. See the Collection Types section of the Swift Programming Language Guide. What does this mean? It mean's that there is no guarantee that the values or keys are stored in the order you create them. The only guarantee you have is that accessing a value by it's key will return that value.

If you require your keys to be accessed in a given order it is up to you to provide that ability.

If you look at the Swift Standard Library Reference it documents what methods we can use on a dictionary.

You have the following properties and functions for working with indexes with dictionaries.

Properties:

startIndex 
endIndex

Functions

func indexForKey(_ key: Key) -> DictionaryIndex<Key, Value>?
func removeAtIndex(_ index: DictionaryIndex<Key, Value>) -> (Key, Value)

Dictionaries also conform to the indexable protocol.

Collection Types

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44