So I have this NSDictionary itemsDict(in Swift):
var itemsDict : NSDictionary = [:] // Dictionary
var Sections : NSArray = [] // Array
itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
print (itemsDict)
This is how the structure of the dictionary looks like:
{
(
News
) = {
a = "www.hello.co.uk";
b = "www.hello.com";
};
(
Sport
) = {
c = "www.hello.co.uk";
d = "www.hello.com";
};
}
From the dictionary above I want to be able to populate an NSArray with only the -
[News,Sports] elements.
I've tried this and a few other methods but they just don't seem to cut it. My Swift skills are not that advanced and I hope this post make sense.
Sections = itemsDict.allKeysForObject(<#anObject: AnyObject#>)
To get an Array of all Strings in your Dictionary's keys, you can use the allKeys property of NSDictionary along with a reduce function, like so:
var itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
let keys = (itemsDict.allKeys as [[String]]).reduce([], combine: +)
println(keys)
Outputs:
[News, Sport]
However, I don't see a good reason to use Arrays of Strings as your Dictionary keys. Instead, I'd just use Strings as keys directly, like so:
var itemsDict = [
"News":["a":"www.hello.co.uk","b":"www.hello.com"],
"Sport":["c":"www.hello.co.uk","d":"www.hello.com"],
]
In which case, getting an Array of the Dictionary's keys is as simple as:
let keys = itemsDict.keys.array
Note: I'm using the keys property here and the allKeys property earlier because this is a native Swift Dictionary while the earlier code is an NSDictionary due to its use of NSArrays for keys.
Related
I have an dictionary and the value containts the array of string as follows
arr = ["key":"["a","b","c","d","e","f","g"]"]
I want the new array to be like
let array = ["a","b","c","d","e","f","g"]
How to parse it
You can access dictionary items in few different ways, the easiest is:
let array = arr["key"]
You may need to conditionally unwrap it
if let array = arr["key"] as? [String] {
// rest of code with array
}
I'm teaching myself swift and am trying to create an array holding dictionaries. The dictionaries are in the following format: String: Any (usually Strings, but sometimes additional arrays of dictionaries).
Is this the correct way to create an array capable of holding dictionaries?
var contentArray: [Dictionary<String, Any>] = []
I went through the question history and saw your edit. indexOfObjectPassingTest is a method on NSArray. You are asking about Array which is a different (though related) type.
Here's how to declare the array:
var contentArray = [[String: Any]]()
Here's how to get the index of an item:
let index1 = contentArray.index(of: aDict)
let index2 = contentArray.index(where: { (some conditions) })
I need to know that how can i make a copy of NSDictionary to NSMutableDictionary and change values of there.
Edit
I ned to know how to modify data of a NSDictionary. I got to know that
Copy data of NSDictionary to a NSMutableDictionary. and then modify data in NSMutableDictionary
let f : NSDictionary = NSDictionary()
var g = f.mutableCopy()
You should initialize the NSMutableDictionary using it's dictionary initializer, here's a quick example in Playground
let myDict:NSDictionary = ["a":1,"b":2]
let myMutableDict: NSMutableDictionary = NSMutableDictionary(dictionary: myDict)
myMutableDict["c"] = 3
myMutableDict["a"] // 1
myMutableDict["b"] // 2
myMutableDict["c"] // 3
Alternatively, you can declare a Swift dictionary as a var and mutate it whenever you want.
var swiftDictioanry : [String:AnyObject] = ["key":"value","key2":2]
The AnyObject value type mimics the behavior of an NSDictionary, if all types are known it can be declared like so:
var myNewSwiftDict : [String:String] = ["key":"value","nextKey":"nextValue"]
I currently have a dictionary that contains 1 value per key. Is it possible to have 2 values per key?
var data = HomeVC.getData()
MyVariables.users = data.users;
MyVariables.img = data.img;
//MY Current dictionary with 1 value and 1 key
for (index, element) in enumerate(MyVariables.users)
{
MyVariables.dictionary[element as! String] = MyVariables.img[index]
}
I'm trying to add values from another array to this dictionary. So in total I would have 3 arrays in the same index position when calling them. 2 values and 1 key
You can use arrays or tuples as values of a dictionary:
var dictionary: Dictionary<String, (ValType1, ValType2)>
dictionary["foo"] = (bar, baz)
println(dictionary["foo"][1])
Instead of that try saving an NSArray as the value for key. The NSArray will be able to save more than 1 values and should suffice.
The lifecycle for a 2 values per key would look something like this
myDict[#"key1"] = value1;
// then set next value
myDict[#"key1"] = value2;
Now your dictionary has lost the first value and you only have access to the last one.
Your code would look something like
for (index, element) in enumerate(MyVariables.users)
{
var savedArray: [Your-Object-Type-Here]? = []
var savedArray = MyVariables.dictionary[element as! String]
if savedArray != nil {
savedArray!.append(MyVariables.img[index])
}
else {
savedArray = []
}
MyVariables.dictionary[element as! String] = savedArray
}
If your values are different types, create a custom class to hold the values. Make your dictionary keys point to objects of your custom class.
I have two separate arrays that I want to import into a dictionary. Order is extremely important because both arrays must match in index
struct MyVariables {
static var users:NSArray!
static var img:NSArray!
}
var data = SearchVC.getData()
MyVariables.users = data.users; //array 1 (key)
MyVariables.img = data.img; //array 2
// Goal is to insert these arrays into a dictionary while maintaing the matching indexes on both arrays
// Dictonary (MyVariables.img, key: MyVariables.users)
A Dictionary does not have a particular order. However, if both arrays have the same length, it is quite easy to iterate over them together:
var dictionary = [NSString: AnyObject]()
for var index = 0; index < data.users.count; index++ {
let img = data.img as! NSString
dictionary[img] = data.users[index]
}
Or, as #robertvojta suggested, use the zip() method:
var dictionary = [NSString: AnyObject]()
for (user, image) in zip(data.users, data.img) {
let img = image as! NSString
dictionary[img] = user
}
The key in a dictionary in swift must be hashable. i.e., not AnyObject.
Assuming you can replace some of your untyped Swift arrays, or cast them like so:
struct MyVariables {
var users:Array<AnyObject>
var img:Array<String>
}
then you can iterate through 1 array using a preferred Swift method and access the second using indexing:
var dictionary = Dictionary<String, AnyObject>()
for (index, element) in enumerate(MyVariables.img) {
dictionary[element] = MyVariables.users[index]
}
Use for loop for travels the array in that as per index access keys and values respective array and add it in dictionary. Its so simple so you can achive your goal using it.
I hope it will help you!