How to create the specified data structure in swift ios? - 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")

Related

Swift 3: how to sort Dictionary's key and value of struct

This is my Struct,by Swift 3. I know the Dictionary is not stored sequence like an Array and that is my problem. I want to get my Dictionary sequence as I set in ViewArray. I can get the ctC Dictionary, but how can i sort the keys or values as i set in ViewArrayplease and appreciate the help.
struct CTArray {
var ctname: String
var ctkey: String
var ctC: [String:String]
}
var ViewArray:[CTArray] = []
ViewArray += [CTArray(ctname: "kerish", ctkey: "KH", ctC: ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"])]
ViewArray += [CTArray(ctname: "tainers", ctkey: "TNN", ctC: ["letGor":"one", "washi":"testing", "monk":"lasth"])]
ViewArray += [CTArray(ctname: "techiu", ctkey: "TCU", ctC: ["22":"tt", "wke":"303", "lenth":"highest"])]
i want to show them in my TableView Cell sorted like these:
the ViewArray[0].ctC.key sorted like [mon, kis, Bat, orlno]
the ViewArray[1].ctC.key sorted like [letGor, washi, monk]
the ViewArray[2].ctC.value sorted like [tt, 303, highest]
It is not clear to me what you are asking, but I'll offer this in case it helps.
I know the Dictionary is not stored sequence like an Array and that is my problem.
If you want to access a dictionary by a certain order of its keys then you can create an array of just the keys in the order you required and use that to access the dictionary. An example is probably easier to follow:
Starting with one of your dictionaries:
let dict = ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"]
print(dict)
this output:
["Bat": "Best", "kis": "aone", "orlno": "bOne", "mon": "Apple"]
which is not what you want. Now introduce a key array and use that to access the dictionary:
let keyOrder = ["mon", "kis", "Bat", "orlno"]
for key in keyOrder
{
print("\(key): \(dict[key]!)")
}
this outputs:
mon: Apple
kis: aone
Bat: Best
orlno: bOne
which is the order you wish.
The same idea can be used anywhere you want to use/show/etc. the keys in a particular order, by using the keyOrder array as part of dictionary access you are making it appear as though the dictionary entries are "stored in sequence" as you put it.
HTH
var object1 = viewArray[0].ctC.flatMap({$0.key})
var object2 = viewArray[1].ctC.flatMap({$0.key})
var object3 = viewArray[2].ctC.flatMap({$0.value})
print(object1)
print(object2)
print(object3)
Outputs:
["Bat", "kis", "orlno", "mon"]
["letGor", "monk", "washi"]
["highest", "tt", "303"]

Create NSMutableDictionsry in Swifty-Json

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()

Nested Dictionary in iOS Swift

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.

iOS 9 JSON Parsing loop

I'm creating an app that should retrieve some JSON from a database.
This is how my JSON looks:
[{"id":"1","longitude":"10","latitude":"10","visibility":"5","timestampAdded":"2015-10-01 15:01:39"},{"id":"2","longitude":"15","latitude":"15","visibility":"5","timestampAdded":"2015-10-01 15:06:25"}]
And this is the code i use:
if let jsonResult = JSON as? Array<Dictionary<String,String>> {
let longitudeValue = jsonResult[0]["longitude"]
let latitudeValue = jsonResult[0]["latitude"]
let visibilityValue = jsonResult[0]["visibility"]
print(longitudeValue!)
print(latitudeValue!)
print(visibilityValue!)
}
As you can see it only gets the first chunk from the JSON and if there are no JSON at all it will crash, but if i want it to count the amount and make an array out of it like this:
var longitudeArray = [10, 15]
var latitudeArray = [10, 15]
And so on...
I also need this to be apple watch compatible so i can't use SwiftyJSON.
What do i do? I really hope you can help me!
Thanks.
SOLVED!
Problems was solved by "Eric D."
This is the code:
do {
if let url = NSURL(string: "YOU URL HERE"),
let data = NSData(contentsOfURL: url),
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
print(jsonResult)
let longitudeArray = jsonResult.flatMap { $0["longitude"] as? String }
let latitudeArray = jsonResult.flatMap { $0["latitude"] as? String }
print(longitudeArray)
print(latitudeArray)
}
} catch let error as NSError {
print(error.description)
}
Thank you soo much Eric!! :-)
You could use flatMap to get an array of your elements:
let longitudeArray = jsonResult.flatMap { $0["longitude"] as? String }
let latitudeArray = jsonResult.flatMap { $0["latitude"] as? String }
etc.
flatMap is like map but unwraps optionals, which is adequate because we need to safely cast the type of the object we get from each dictionary in the json array.
$0 represents the object in the current iteration of flatMap of the array it's applied to.
If you're currently using SwiftyJSON, then that would be:
let longitudeArray = jsonResult.flatMap { $1["longitude"].string }
let latitudeArray = jsonResult.flatMap { $1["latitude"].string }
because .string is SwiftyJSON's optional String value getter.
But as you said, you don't want to use it (anymore), so you need to use NSJSONSerialization to decode your JSON data, there's plenty of examples on the Web and on SO. Then you will be able to use my original answer.
You're already getting an array with all of the elements (not just the first one. you're simply only accessing the first one). jsonResult is an array of dictionaries. Each dictionary (in this case, based on the json you provided) contains these elements: id, longitude, latitude, visibility and timestampAdded. In order to access each of them, you can simply loop over jsonResult and access the i'th element (and not always the 0 element). This will also prevent the crash you're experiencing with the json is blank or invalid (since you'll only be going over the valid elements in jsonResult.
This will give you the flexibility to create the custom arrays you wish to create (in order to create an array of all of the longitudes, for example, you will simply add that element to the new array while looping over jsonResult). However, if you'd like to save yourself the trouble of manually building these arrays and assuming you have control over the json structure, I would recommend changing the received json to the relevant structure (a dictionary or arrays instead of an array of dictionaries), so it would better fit your needs and provide you the results in the relevant format right "out of the box".

Create an array in swift

I'm searching really much, but maybe I can't understand the results.
I found only that a array in SWIFT have as index int-values
var myArray = [String]()
myArray.append("bla")
myArray.append("blub")
println(myArray[0]) // -> print the result bla
But I will add a String with an String as index-key
var myArray = [String:String]()
myArray.append("Comment1":"bla")
myArray.append("Comment2":"blub")
println(myArray["Comment1"]) // -> should print the result bla
How should i declare the array and how I can append a value then to this array?
Your second example is dictionary
myArray["key"] = "value"
If you want array of dictionaries you would have to declare it like this
var myArray: [[String: String]]
Your first example is an array. Your second example is a dictionary.
For a dictionary you use key value pairing...
myArray["Comment1"] = "Blah"
You use the same to fetch values...
let value = myArray["Comment1"]
println(value)
You got the concept of array in the first example but for the second one you need a dictionary as they operate on key value pair
// the first String denotes the key while the other denotes the value
var myDictionary :[String:String] = ["username":"NSDumb"]
let value = myDictionary["username"]!;
println(value)
Quick reference for dictionaries collection type can be found here

Resources