Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Collections and Control Flow Dictionaries in Swift Working With Dictionaries

How to grab the "key" value from a dictionary item?

If i have a dictionary and i want to grab the key value rather than the value value, how can I do that? For example, i want to assign the word "color" to the keyName variable.

// Enter your code below

var myDictonary:[String: String] = ["Color": "Red"];
var keyName:String = myDictionary["Color"].key;

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points


I am not understanding your question, but here is my best try:

If you want to know the keys of your dictionary, the dictionary itself has a property called "keys". This property is returns an array of all the keys in your dictionary. So you can iterate through them till you find the one you want.

let numbersDictionary: [String: Int] = ["one" : 1, "two" : 2, "three": 3]
let keys = numbersDictionary.keys

var keyName = ""

for key in keys where key == "one" {
     keyName = key

print("Key Name: \(keyName)")

Let me know if this is something you are looking for.

Jhoan, that was exactly what i was looking for! Thank you.

Is this the only way of doing this? I'm still new to Swift, although the Syntax for that looks similar to how you would accomplish that with a JS object.

Jhoan Arango
Jhoan Arango
14,575 Points

As far as I know, "keys" is the only and best to get the dictionary keys yes. Welcome to Swift. Hope you enjoy this new journey.