Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.

dictionary.swift
// 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

Hello,

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.