Nested Dictionary in iOS Swift - ios

I want to save a data in a dictionary in below format and then have to convert it into json.
[{"id":"1",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"123"},
{"id":"2",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"234"}
]
It got dictionary and single strings both within a dictionary. Here is what I'm trying, but unable to get the desirable result.
var myDictionary = Dictionary<String, AnyObject>()

let arrOfData = [["id":"1","pass":"123","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]],
["id":"2","pass":"234","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]]]
Here u can see the array of dictionary like Array<Dictionary,AnyObject> if you want to store in a single dictionary you can use it like let dict2 = ["data":arrOfData] Now this will convert into a single dictionary.

Related

check which dictionary keys corresponding arrays contain a certain string

I have a dictionary like this dict = [String:[String]]
I want to be able to check if a given string is contained in any of the arrays in the dictionary. If so I would like to then gather the keys for those arrays and create a new array of those values.
Here searching for the word "so":
let dict = ["hi":["so", "im"], "fi": ["to", "le"]]
let keys = Array(dict.filter{ $1.contains("so") }.keys)
print(keys)
For your second request where a match is enough:
let values = ["hi":["so", "im"], "fish": ["to", "ler"]]
let keys = Array(values.filter{ $1.contains{ string in string.contains("s") } }.keys)
print(keys)

How to create the specified data structure in swift ios?

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 and array inside the value of dictionary

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
}

How to conver my JSON to NSArray

I'm new to Swift, i started learning on the new Swift 3
I've this as NSArray
var arrayName: NSArray = NSArray()
arrayName = ["name 1","name 2","name 3","name 4","name 5"]
The tableview currently prints those items above.
I want to get JSON online from http://api.androidhive.info/contacts/
and append name items to be the content of my NSArray arrayName
So first get the json data in a shared url session. Make sure to check for the success flag in the completion closure. Once you've got the data you can deserialize it with the JSONSerialization class, https://developer.apple.com/documentation/foundation/jsonserialization. So now you have the json in an object. Now you can convert it to a dictionary. In the dictionary traverse into "contacts" with the dictionary["contacts"] syntax. Next, cast the new object as a [[String: AnyObject]] which means array of dictionaries. From there, you can loop through and get the name property. Note: instead of casting the object as [[String: AnyObject]] you could also cast it as! NSArray.

Swift NSDictionary get 0th value without knowing key name

I have an NSDictionary that has a key like messageID5 and the value has three key/value pairs.
I know the NSDictionary only has 1 value in it because I limited my query to 1. But I don't know the name of the key. I just want the value, but I can't access it like an array [0]. You can access it just fine in PHP or Python. I've been trying a lot of different solutions for this basic problem, but a lot of them seem overly messy. anyValue[0] gives me a type error.
If you don't know your dictionary keys, you can get your NSDictionary allKeys.first property or allValues.first:
let dict = NSDictionary(dictionary: ["a":["b":1]])
let subDict = dict[dict.allKeys.first] as? [String:Any] ?? [:] // ["b": 1]
// or
let subDict = dict.allValues.first as? [String:Any] ?? [:] // ["b": 1]
The first thing to acknowledge is that key/value pairs in dictionaries does not maintain any specific order - this is required for an optimization in access to the contents of this structure.
As for your case if you're 100% sure you'll have only one value inside your dictionary you can use .allValues.first to retrieve the contained value. If your know that the type of your value is NSDictionary the whole code may look like this:
let childDictionary = rootDictionary.allValues.first as? NSDictionary
I suggest using (dictionary as Dictionary).values.first. That returns an optional, since it can fail if the dictionary is empty.
(Note that I edited this answer to cast the dictionary from an NSDictionary to a Dictionary so you an use the values property. NSDictionary doesn't have a values property, but Dictionary does.)

Resources