Get dictionary from NSMutableArray of dictionary - ios

I'm trying to get a NSMutableDictionary from a NSMutableArray.
I set my array this way:
let test : NSMutableDictionary = NSMutableDictionary()
test.setValue("Monday", forKey: "day")
test.setValue("7PM - 8PM", forKey: "hour")
self.availabilityArray.add(test)
let test1 : NSMutableDictionary = NSMutableDictionary()
test1.setValue("Saturday", forKey: "day")
test1.setValue("8PM - 10PM", forKey: "hour")
self.availabilityArray.add(test1)
let test2 : NSMutableDictionary = NSMutableDictionary()
test2.setValue("Sunday", forKey: "day")
test2.setValue("2PM - 8PM", forKey: "hour")
self.availabilityArray.add(test2)
And in another method I try to get the "day" and "hour" value to set them in a UILabel.
I've tried to do this :
let dico = self.availabilityArray[i] //i being the index of a loop, not important here
self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day") // This line does not work, I want to do something like that.
So how can I get the content of my NSMutableArray for a precise index as a NSDictionary ?
Thanks.

Thanks to Larme I found the solution, I juste replace
self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day")
With
self.dayNameLabel.text = (dico as! NSMutableDictionary).object(forKey:"day") as! String?

You should use swift 2 (or 3) objects.
declare your array like that :
var availabilityArray: [[String: String]] = []
then create your dictionaries :
var test: [String: String] = [:]
test["day"] = "Monday"
test["hour"] = "7PM - 8PM"
var test1: [String: String] = [:]
test1["day"] = "Saturday"
test1["hour"] = "8PM - 10PM"
var test2: [String: String] = [:]
test2["day"] = "Sunday"
test2["hour"] = "2PM - 8PM"
add them to the array :
self.availabilityArray.append(test)
self.availabilityArray.append(test1)
self.availabilityArray.append(test2)
and finally access the object :
let dico = self.availabilityArray[0]
self.dayNameLabel.text = dico["day"]
dico["day"] is optional, so use dico["day"]! or use a real unwrap with if let

Related

how to append an array of dictionaries to another array

I tried to append an array of dictionaries which are coming from server to a globally declared array.but i am getting an error like "Cannot convert value of type '[Any]' to expected argument type '[String : Any]'"if anyone helps me would be great.Thanks in advance
var pro = [[String:Any]]()
var productsdetails = Array<Any>()
productsdetails = userdata.value(forKey: "products") as! Array
print("response\(productsdetails)")
self.pro = self.pro.append(productsdetails)
print(self.pro)
Use this code like below, i hope this works
var pro = [[String:Any]]()
if let productsdetails = userdata.value(forKey: "products") as? [[String:Any]] {
print("response\(productsdetails)")
self.pro.append(productsdetails)
print(self.pro)
}
to solve this iterate
var pro = [[String:Any]]()
if let productsdetails = userdata.value(forKey: "products") as? [[String: Any]] {
for details in productsdetails {
pro.append(details)
}
}
or you may use directly self.pro = productsdetails if you not to want iterate
**image shows [String : String] as I have used [String : String] instead of [String : Any]*
You can try this: (Swift-4.2)
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(item)
// replace back into `data`
data["items"] = existingItems
}
Answer same as: Append to array in [String: Any] dictionary structure
Can you show us your response which has key products? As there is mismatch with the variable pro and productdetails. As i see pro holds values as "Array of Dictionary with key as String type and Value as Any type" which again has Array above it and productdetails is expecting Array of Any type not the Array of Dictionary Type. Assuming your products has Array of String Type or can be even a class object type you can do it as below.
var pro = Array<Any>() //Or You can make Array<String>() or Array<CustomClass>()
var userdata:[String:[String]] = ["products":["One","Two","Three"]]
var productsdetails = Array<Any>()
productsdetails = userdata["products"] ?? []
print("response\(productsdetails)")
pro.append(productsdetails)

Swift Passing array of dictionary to NSMutableArray

I am trying to pass swift array of dictionaries to the NSMutableArray. But I am getting error "Cannot convert value of type [[String : Anyobject?]] to expected argument type NSMutableArray". Below is the code:
var ary : [[String:AnyObject?]] = []
var mutableDictionary = [String: AnyObject?]()
for c in buffer {
mutableDictionary.updateValue(c.Name, forKey: "name")
mutableDictionary.updateValue(c.Number, forKey: "phoneNumber")
mutableDictionary.updateValue(c.id, forKey: "id")
ary.append(mutableDictionary)
}
Now passing this "ary" to the Objective C method as a NSMutableArray!
Manager.sharedInstance().List(ary)
Replica of your issue:
var ary : [[String:AnyObject]] = []
var mutableDictionary = [String: AnyObject]()
var mutableArray:NSMutableArray!
for _ in 0...4 {
mutableDictionary.updateValue("adsf", forKey: "name")
mutableDictionary.updateValue("dsf", forKey: "phoneNumber")
mutableDictionary.updateValue("sdfd", forKey: "id")
ary.append(mutableDictionary)
}
mutableArray = NSMutableArray(array: ary)
Removing the optional did the trick!
// try like this
Manager.sharedInstance().List(NSMutableArray(array: ary as! NSArray))

How to store Array in NSUserDefault in Swift?

So I've been trying for a few hours for a way to store an array to NSUserDefault and print them to the cells but the data is not saving as an array, it basically only saves one value at a time.
var emailData = [String]()
var passwordData = [String]()
#IBAction func addPressed(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
emailData.append(addEmail.text!)
passwordData.append(addPassword.text!)
var storedEmail = defaults.objectForKey("emailData") as? [String] ?? [String]()
var storedPasswords = defaults.objectForKey("passwordData") as? [String] ?? [String]()
// then update whats in the `NSUserDefault`
defaults.setObject(emailData, forKey: "emailData")
defaults.setObject(passwordData, forKey: "passwordData")
// call this after you update
defaults.synchronize() /*
NSUserDefaults.standardUserDefaults().setValue(addEmail.text, forKey: "email")
NSUserDefaults.standardUserDefaults().synchronize()
*/
}
So basically the data is not saving.
You can store Array too, by this way
let userDefault = NSUserDefaults.standardUserDefaults()
let arr = ["abc","xyz","pqr"]
userDefault.setObject(arr, forKey: "arr")
userDefault.synchronize()
let data = userDefault.objectForKey("arr") as! [String]
Save the Swift Array in Swift.
let kUserDefault = NSUserDefaults.standardUserDefaults()
kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
Get Array
1. arrayForKey : You getting Swift Array
kUserDefault.arrayForKey("nameArray")!
2. objectForKey : You getting NSArray
kUserDefault.objectForKey("nameArray")!
3. valueForKey : You getting NSArray
kUserDefault.valueForKey("nameArray")
It is possible to store arrays in NSUserDefaults. But separating email and password in separate array is not suitable. You should store it as one object since they are related.
In your case an array of Dictionary objects is better, which is possible to store in NSUserDefaults as well, which you can retrieve as an array of Dictionary.
Here is the sample:
let userDefault = NSUserDefaults.standardUserDefaults()
var storedCredentials = userDefault.objectForKey("credentials") as? [[String:AnyObject]] ?? [[String:AnyObject]]()
let email =
[
"email" : addEmail.text!,
"password": addPassword.text!
]
storedCredentials.append(email)
userDefault.setObject(storedCredentials, forKey: "credentials")
userDefault.synchronize()
You can't save an array of [String] in NSUserDefault, if you look at the documentation :
For NSArray and NSDictionary objects, their contents must be property
list objects.
So what you can do is convert your [String] into NSData then save it into NSUserDefault.
// Store it as NSData
var emailData = [String]()
emailData.append("email1")
emailData.append("email2")
let emailIntoNSData = NSKeyedArchiver.archivedDataWithRootObject(emailData)
NSUserDefaults.standardUserDefaults().setObject(emailIntoNSData, forKey: "emailData")
// Retrieve it :
let emailFromNSData = NSUserDefaults.standardUserDefaults().objectForKey("emailData") as? NSData
if let emailFromNSData = emailFromNSData {
let emailArray = NSKeyedUnarchiver.unarchiveObjectWithData(emailFromNSData) as? [String]
if let emailArray = emailArray {
NSLog("Email Data : \(emailArray)") // ["email1","email2"]
// do something…
}
}

Create mutable Dictionary with dynamic value/keys in SWIFT

I need to create a Dictionary with dynamic keys.
At the end I need a Dictionary
I tried to use:
var animDictionary:[String:AnyObject]
for position in 1...10
{
let strImageName : String = "anim-\(position)"
let image = UIImage(named:strImageName)
animDictionary.setValue(image, forKey: strImageName) //NOT WORK
//BECAUSE IT'S NOT A NSMUTABLEDICTIONARY
}
So I tried:
var animMutableDictionary=NSMutableDictionary<String,AnyObject>()
for position in 1...10
{
let strImageName : String = "anim-\(position)"
let image = UIImage(named:strImageName)
animMutableDictionary.setValue(image, forKey: strImageName)
}
But I don't find the how to convert my NSMutableDictionary to a Dictionary. I'm not sure it's possible.
In the Apple doc, I found :
I don't know if it's possible to use it in my case.
Xcode 11 • Swift 5.1
You need to initialize your dictionary before adding values to it:
var animDictionary: [String: Any] = [:]
(1...10).forEach { animDictionary["anim-\($0)"] = UIImage(named: "anim-\($0)")! }
Another option is to use reduce(into:) which would result in [String: UIImage]:
let animDictionary = (1...10).reduce(into: [:]) {
$0["anim-\($1)"] = UIImage(named: "anim-\($1)")!
}

Appending Dictionary to Swift Array

I have this Swift code in which I'm trying to append a Dictionary to Array.
var savedFiles: [Dictionary<String, AnyObject>] = []
var newEntry = Dictionary<String,AnyObject>()
if let audio = receivedAudio?.filePathURL {
newEntry["url"] = audio
}
newEntry["name"] = caption
savedFiles.append(newEntry! as Dictionary<String,AnyObject>)
This gives me an error on last line (in append) Cannot invoke 'append' with an argument list of type '(Dictionary<String, AnyObject>)'
Any idea? I also tried remove force unwrapping as well.
Please try this:
var savedFiles: [[String: AnyObject]] = []
var newEntry: [String: AnyObject] = [:]
if let audio = receivedAudio?.filePathURL {
newEntry["url"] = audio
}
newEntry["name"] = caption
savedFiles.append(newEntry)
Hi just tried on playground its working, only you should know this: audio could be nil any time, in that case this key value pair won't be added in newEntryDictionary.
var savedFilesDictionary = [[String: AnyObject]]()
var newEntryDictionary = [String: AnyObject]()
var receivedAudio = NSURL(string: "/something/some")
if let audio = receivedAudio?.filePathURL {
newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = "some caption"
savedFilesDictionary.append(newEntryDictionary)
As of Swift 4, the correct way to work with dictionaries:
Declare empty dictionary (associative array):
var namesOfIntegers = [Int: String]()
Append to dictionary:
namesOfIntegers[16] = "sixteen"
Check if dictionary contains key:
let key = 16
if namesOfIntegers.keys.contains(key) {
// Does contain array key (will print 16)
print(namesOfIntegers[key])
}
See more, straight from Apple: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
Absolutely no problem:
var savedFiles: [Dictionary<String, AnyObject>] = []
var newEntry = Dictionary<String, AnyObject>()
newEntry["key"] = "value"
savedFiles.append(newEntry)
Although this is the "Swifty"-Style:
var savedFiles = [[String: AnyObject]]()
var newEntry = [String: AnyObject]()
newEntry["key"] = "value"
savedFiles.append(newEntry)
I am using Xcode 7.2.1.
var savedFilesDictionary = [String: AnyObject]()
var newEntryDictionary = [String: AnyObject]()
if let audio = receivedAudio?.filePathURL {
newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = caption
savedFilesDictionary.append(newEntryDictionary)
Try this.

Resources