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

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)

Related

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.

Add Multiple Key-Value pairs to an existing Dictionary [duplicate]

This question already has answers here:
Dictionary extension to return a combined dictionary
(3 answers)
Closed 6 years ago.
I created a dictionary and it already has several values, however, I now want to add more. And I know that I can add key-value pairs like this:
var Dict = [Int: String] ()
Dict = [1: "one", 0: "zero"]
Dict[2] = "two"
Dict[3] = "tres"
But I was wondering how to add a lot of pairs at the same time, because if they are too many and it would be a really long process to do it like that.
I know this can be done in an Array like this:
Array += [1, 2, 3, 4, 5, 6]
But don't know if the same can be done for dictionaries.
There are some tricky things you can do with flatmap, but generally, Swift's Dictionary does not have the append(:Collection) method that Array does, because appending an unknown Dictionary could give you duplicate keys and cause errors. If you want to append another Dictionary, you'll have to iterate over it. This code
var dict1 : [String:String] = ["one" : "two", "three" : "four"]
var dict2 : [String:String] = ["one" : "two", "three" : "five"]
for(key, value) in dict2 {
dict1[key] = value
}
will replace all duplicate keys with the values in the second Dictionary. If you have no duplicate keys, this will do exactly what you want. If you DO have duplicate keys, then determine which values take priority, and make sure those values are in your dict2.

How to get key of NSDictionary [duplicate]

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.

Swift iOS 8, first value of NSDictionary

I have NSDictionary, I know it only has one key and one value, how can I directly get the first value from it?
thanks,
If you have a Swift Dictionary and you know you have exactly 1 key/value pair you can do this:
var dict = ["aaa":"bbb"]
let v = dict.values.first!
If you have more than 1 key/value pair then there is no "first" value since dictionaries are unordered. If you have no key/value pairs this will crash.
If you have an NSDictionary, you can use allValues.first!, but you'll have to cast the result because the value will be an AnyObject:
var dict:NSDictionary = ["aaa":"bbb"]
let v = dict.allValues.first! as! String
or:
let v = dict.allValues[0] as! String
Cast to a Swift Dictionary if it isn't one already. Then use the values property, cast to an Array, and get index 0.
let v = Array(myDictionary.values)[0]

Swift: array of dictionaries has count of 1 after initialization but should have 0 [duplicate]

This question already has answers here:
Swift: dictionaries inside array
(4 answers)
Closed 8 years ago.
var persons = [Dictionary<String, String>()]
println(persons.count)
prints 1. I see that there is an empty dictionary inside the array when it is initialized but is there a way to avoid that and having 0 elements instead of 1? Later I need to be able to do:
persons.append(["firstName": "Foo", "lastName": "Bar"])
Any ideas?
By using this:
[Dictionary<String, String>()]
you are creating an array with one element Dictionary<String, String>()
The correct way is to move the parenthesis after the square brackets:
[Dictionary<String, String>]()
That declares an array of type Dictionary<String, String>, and instantiate it.
Equivalent way of creating it is:
Array<Dictionary<String, String>>()
Just place brackets outside:
var persons = [Dictionary<String, String>]()
Shouldn't it be
var persons = Dictionary<String, String>()
println(persons.count)
or
var persons = [String : String]()
println(persons.count)
but not both syntaxes at the same time?
https://developer.apple.com/library/mac/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.html