I want to create a NSMutableDictionary using Swifty-Json.
I have declared dictionary like this
var arrTest = Array<JSON>()
var testDict : JSON = [:]
testDict.dictionaryObject?.updateValue(arrTest[0]["test"][indexPath.item]["xyz"], forKey: "abc")
Now I am unable to setValueForKey in this Dictionary.
Can Someone tell me how to create a NSMutableDictionary using SwiftyJson and also how to insert, update and delete values in this dictionary.
Thanks in advance
Don't use NSMutableDictionary in Swift, use Swift built-in type Dictionary instead. Declaring it as var will make it mutable.
You also don't use updateValue for Dictionary, simply use a subscript:
var testDict : [String : AnyObject] = [:]
let key = "abc"
let value = arrTest[0]["test"][indexPath.item]["xyz"]
testDict[key] = value
// add object
let testobj = ["qwe" : arrTest[0]["test"][indexPath.item]["xyz"]]
dictSelectedOption = JSON(testobj)
//remove objects
dictSelectedOption.dictionaryObject?.removeAll()
Related
I am trying to create a particular data structure as specified below in Swift.
[{"productId":1,"qty":3},{"productId":2,"qty":1},{"productId":3,"qty":5},{"productId":4,"qty":30},{"productId":5,"qty":13}]
Can some one guide me how to achive it..... I need to add and remove the data structure.
Thanks in advance.....
It is an Array of Dictionaries.
Define it like this :
var dataStructure = [[String: Any]]()
To add something :
var newData = [String: Any]()
newData["productId"] = 1
newData["qty"] = 1
dataStructure.append(newData)
To delete :
dataStructure.remove(at: indexYouWantTodeleteInInt)
It is called as dictionary in swift.
The declaration part can be as follows:
var params: [String:Any]
We can also use like:
var params: [String:Any] = ["user_id" : AppConfiguration.current.user_id]
Now to add key-value pair in it you can do as follows:
params["form_id"] = form_id!
params["parent_category_id"] = id
params["device_token"] = getDeviceToken()
params["app_version"] = APP_VERSION
params["app_device_type"] = originalDeviceType
to remove a key-value pair:
params.removeValue(forKey: "parent_category_id")
to update any value of particular key:
params.updateValue("10", forKey: "form_id")
if the above key is already present it updates the value and if not then it adds a new key to the dictionary
The Above explained part is dictionary. Now you need the data-structure as array of dictionary so you need to declare as
var params: [[String:Any]]
you can perform all the operations you can perform on an array but the value you will get at a particular index will be of type dictionary which I explained above.
Hope this helps you understand what is dictionary and what is array of dictionaries.
In your case you can also write [String: Int] instead of `[String:Any]' but it will restrict you to only have integer values with respect to the keys.
Swift developers usually use Structs in order to create a data structure from a JSON reponse. From Swift 4, JSON parsing has become very easy. Thanks to Codable protocols.
From the above given answer, you can create something like this.
MyStruct.Swift
import Foundation
typealias MyStruct = [[String: Int]]
You can then parse by calling the following method.
let myStruct = try? JSONDecoder().decode(MyStruct.self, from: jsonData)
You can add value by using this.
var newProduct = [String: Any]()
newProduct["productId"] = 941
newProduct["qty"] = 2
myStruct.append(newProduct)
To remove the data
myStruct.remove(at:"Some index")
I have a Dictionary and i want to save it to NSUserDefaults(or something else so I can have access to my variables after i have terminated the app) , I found an example:
var saved = NSUserDefaults.standardUserDefaults()
let dict = ["Name": "Paul", "Country": "UK"]
saved.setObject(dict, forKey: "SavedDict")
But when i used it to mine Dictionary it didn't work. (maybe because my dictionary it's a little bit different)
My Dictionary is made like this:
var userDictionary = [Int : Event]()
struct Event {
var sensorName: String
var sensorType: String
var sensorSub: String
}
And i add elements like this:
userDictionary[value] = Event(sensorName: "first", sensorType: "Temp", sensorSub: "Third")
And here is what i tried to do so I can store it.
saved.setObject(userDictionary, forKey: "valueDictionary")
And I get this error:
Cannot convert value of type '[Int : SensorsView.Event]' to expected
argument type 'AnyObject?'
To avoid this error I did this:
self.saved.setObject(self.userDictionary as? AnyObject, forKey: "valueDictionary")
But I can't retrieve what i saved
Unfortunately this question didn't help me after some comments i believe that the goal here is to convert my dictionary to Data (or something else) and after i retrieve it i convert it back to Dictionary
Try to convert the data to NSData and then retrieve like so:
/// Save
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(object), forKey: key)
/// Read
var data = NSUserDefaults.standardUserDefaults().objectForKey(key) as NSData
var object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [String: String]
What i think is from the link below you will be able to store the Dictionary into NSUserDefaults
Swift NSUserDefaults not saving Dictionary?
or
Saving dictionary into NSUserDefaults may help
I managed to save my custom Dictionary using Realm!
Instead of a struct I use a different class like this:
import RealmSwift
class Sensors : Object {
dynamic var sensorName = ""
dynamic var sensorType = ""
dynamic var sensorSub = ""
}
and then I fill it like this:
var useOfRealm = try! Realm()
var allSensors = useOfRealm.objects(Sensors.self)
var saving = Sensors()
func fillThis() {
try! useOfRealm.write {
saving.sensorName = "something"
saving.sensorType = "something"
saving.sensorSub = "something"
useOfRealm.add(saving)
}
}
Use the function with parameters so you can fill the 'Dictionary' Dynamically.
Use allSensors so you can retrieve everything that you want.
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've been recently trying to figure out how to init a Dictionary in swift like i used to do in Objective-c:
NSMutableDictionary *loginDictionary = [[NSMutableDictionary alloc] initWithObjects:#[UsernameTextfield.text,PasswordTextfield.text] forKeys:#[#"username",#"password"];
i tried to write it in Swift :
let userDictionary = NSMutableDictionary.init(object: [usernameTextField.text,passwordTextField.text], forKey: ["username","password"])
But i get an error:
Contextual type AnyObject cannot be used with array literal.
First of all, you have to use the same method, with objects and forKeys (note the plural).
Then you need to tell the compiler what type is each object, in your case it's strings from Optional text labels, so you could do something like this:
if let name = usernameTextField.text as? String, let pass = passwordTextField.text as? String {
let userDictionary = NSMutableDictionary(objects: [name, pass], forKeys: ["username", "password"])
}
You are Passing Objects and Keys in NSMutableDictionary as below, replace your code as below.
let userDictionary = NSMutableDictionary(objects: [usernameTextField.text,passwordTextField.text], forKeys: ["username","password"])
In the Swift PDF file released by Apple i came thorough this code
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
Here what is the use of creating a let (constant) object with empty array, where we cannot insert any values into it in next line ??!!
while teaching objective- c they start teaching like
NSArray *arrayObj = [[NSArray alloc] init]
if we declare like this we cannot add objects after initialisation
similarly they are teaching us how to initialise an array or dictionary objects
one more difference is if we allocate an empty array then we can assign another array with this.
let will not allow you to assign another array to it also
let emptyArray = [String]()
let/var filledArray = ["stack", "overflow"]
emptyArray = filledArray // will give you an error
Not much use, but the value can be copied:
let emptyDictionary = [String: Float]()
var otherDictionary = emptyDictionary
otherDictionary["a"] = 0.5
The property declaration sets them to a default, but you could actually change the value to something else in init. This would only be the case for class properties, not inline properties though.
Here's an example in a class scope where a let property can have a default but be changed:
class Whatever {
let testArray = [Int]()
init() {
testArray = [0,1,2]
}
}