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

Mike Chael
Mike Chael
891 Points

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
MOD
Jhoan Arango
Treehouse Moderator 12,878 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.

Mike Chael
Mike Chael
891 Points

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
Treehouse Moderator 12,878 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.