How to get key of NSDictionary [duplicate] - swift

This question already has answers here:
Firebase - how to get the key value in observeEventType = Value
(3 answers)
Closed 6 years ago.
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?

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.

Related

How do I filter an array of a class in swift that returns an array of a subclass of the original class? [duplicate]

This question already has answers here:
Filter out subclasses from superclasses array
(2 answers)
Closed 5 months ago.
How do I filter an array of objects of a certain class and return the results to an array of of a subclass of the original class? Specifically to filter and array of CKRecord and return the results to an array of [CKShare], like thus:
let records = [CKRecord]()
let shares: [CKShare] = records.filter({ $0 is CKShare })
The code above generates a code-time error message "Cannot assign value of type '[CKRecord]' to type '[CKShare]'".
I wonder if I could use a map method to work with the filter method to do what I want to do, or a version of the map method.
Use compactMap for this.
let shares = records.compactMap({ $0 as? CKShare })
If you want to filter also your records then you can write like this.
//Replace $0.isEnable with your condition, if that is true then cast it for sub class CKShare else return nil
let shares = records.compactMap({ $0.isEnable ? $0 as? CKShare : nil })

Getting Key from Dict as String in Swift

New to coding here.
I have a dict with strings as keys and arrays of integers as values and I'm trying to get, from a given key, the String of that key. Not the value of the key, but the key itself. Now, I would just put an extra String into the array and call that, but my Xcode seems to have a bug where it really doesn't like having mixed type arrays and it doesn't work.
An example looks like this:
var allDict: [String: [Int]] = [:];
allDict.updateValue([1, 2, 3], forKey: "BAGEL"]);
allDict.updateValue([4, 5, 6], forKey: "DONUT"]);
allDict.updateValue([7, 8, 9], forKey: "MACARON"]);
I can get the values of each array quite fine with allDict["DONUT"]![1] //prints 5 for example, but what I want is to get the String of the key.
i.e. I would like to print DONUT using allDict["DONUT"]!
Is this possible? Thank you in advance!
It looks like you know your keys going in, in this example.
Here are a few ways you might recover your keys in a useful way, though:
Say you have a dictionary
var dict: [String: Int] = ...
You could get the array of keys:
let keys = dict.keys // keys is of type [String]
You can iterate over keys and values:
for (key, value) in dict {
...
}
You can merge dictionaries of and choose values from either dictionary when keys collide:
let mergedDict = dict.merge(otherDict) { leftValue, rightValue in
return leftValue
}
Addressing a version of your original question briefly:
Say you have the value for a certain key:
let donutValue = dict["DONUT"]
and somewhere else, where you lo longer have access to the key, you want to recover it from the value somehow. The best you could do is attempt to find the key by searching through the dictionary with the value you have.
var searchResult = dict.first { key, value in
return value == donutValue
}
This assumes the values in your dictionary are Equatable. Otherwise, you have to write some function or logic to figure out whether or not you've found that value in the dictionary corresponding to donutValue.

the exact replacement for dictionaryWithObjects: forKeys: in swift [duplicate]

This question already has answers here:
Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`
(5 answers)
Closed 5 years ago.
I am converting code from objective c to swift, I am unable to find the replacement for dictionaryWithObjects: forKeys: anything that I try is not giving the expected output.
I tried dict.updateValue(values[i]!, forKey: keys[i] as! String )
inside a for loop, but I realised that there are constant no of elements in keys(26) but for values(20,000) it has many elements.
So please help me!!
Sorry if I'm wrong, Thanks in Advance.
for i in 0..<alphabets.count {
in_memory_prediction.updateValue(prediction[i]!, forKey: alphabets[i] as! String)
}
You should be able to update dictionary directly even the value is object
var eachKey = alphabets[i] as! String
in_memory_prediction[eachKey] = prediction[i]!

Dictionary fetch all keys and use them as Array [duplicate]

This question already has answers here:
Array from dictionary keys in swift
(12 answers)
Closed 5 years ago.
I use method .keys from the Dictionary to fetch all keys that are in the dictionary and work with them like Array.
Problem when i fetch it .keys it returns LazyMapCollection how i can convert it to Array of keys.
Precondition:
User is structure with funds not nil dictionary [String:String].
let keys = user.funds?.keys
How should i convert keys to be Array?
Maybe using map will help:
let dictionary: [String:String] = [:]
let keys: [String] = dictionary.map({ $0.key })
Don't like map? Go this way:
let dictionary: [String:String] = [:]
let keys: Array<String> = Array<String>(dictionary.keys)

Swift import dictionary to tableviewcell

I am trying to create a table view to show the content of a dictionary called tableText<String, String>. But in the cellForRowAtInSection method, when I do something like
let obj = tableText[indexPath.row]
It gives me a error saying that
cannot subscript a value of type 'Dictionary<String, String> with an index of Int.
I also tried things like
let obj = tableText[indexPath.row] as? NSDictionary
but the error is still there.
Could you help me with this please?
If you just want the values, you can get an array of values from the dictionary and used the indexPath.row on that array.
if let text = tableText.values[indexPath.row] as? String {
cell.textLabel.text = text
}
Obviously if you need them to be sorted you would have to sort them as dictionary is not sorted based on keys.
If you wanted them sorted alphabetically, you could do this
let sortedText = tableText.values.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
And use this sortedText array as your datasource