Wayne Filkins Wayne Filkins - 3 months ago 9
Swift Question

How to get key of NSDictionary

I'm using Firebase and getting a snapshot and when I print it I get this:

{
"-KOx03Q1f1Tl9AiWxNlg" = {
message = ".";
senderId = B6WI1xkEBXd4cwYkYFQRneEvPBV2;
};
}


I want to get the key, the value of
-KOx03Q1f1Tl9AiWxNlg
key. I can't figure out how to get it. I can print it as!
NSDictionary
and it looks exactly the same so it seems to be in that form...but I didn't know
NSDictionary
items had a key or name like that. Can anyone explain this?

Answer

You are using NSDictionary, so you can get array of all keys using allKeys property of NSDictionary

let keys = yourDic.allKeys as! [String]

In Swift 2.2 and later

let keys = myDictionary.keys as! [String]

Note: Access the first object of keys array to get -KOx03Q1f1Tl9AiWxNlg key.