I am trying To add Array In My Dictionary.
How to add Details2 In ProductDetails of Details1 So I can Display On TableView Which Each row is Containing Collection View.
(((((self.completeDetailsArray[index] as! NSDictionary).mutableCopy()) as! NSMutableDictionary).value(forKey: "productDetails") as! NSArray).mutableCopy() as! NSMutableArray).addObjects( from: productArray )
I tried This One Which is not working
let productArray : NSArray = responseResult.value(forKey: "details2") as! NSArray
let oldProductDict : NSMutableDictionary = (self.completeDetailsArray[index] as! NSDictionary).mutableCopy() as! NSMutableDictionary
let oldProductArray : NSArray = oldProductDict.value(forKey: "productDetails") as! NSArray
let completeProductArray = oldProductArray.addingObjects(from: productArray as! [Any])
oldProductDict.setValue(completeProductArray, forKey: "productDetails")
self.completeDetailsArray.replaceObject(at: index, with: oldProductDict)
let oldProductDict2 : NSDictionary = self.completeDetailsArray[index] as! NSDictionary
print("oldProductDict2",oldProductDict2)
This is Working Is This Correct Solution Or I can Use Any Other Way
You can get each element of details1 like
var new = details1[0]
and now add
new["productDetails"] = details2
and add new into main array like
details[0] = new
The easy way to convert JSON to model class or struct using JSONExport
then you can make this like that
let details2:[ProductDetails] = [ProductDetails]()
details1.productDetails = details2
Related
I am getting values from and Array[String:Any] type array in a for loop but it is getting crashed when going on first line in for loop .
Actually I have created an array (Array[String:Any]) Type and now I am getting all the values of this array to show on tableview but it is getting crash in for loop.
var ticketArray = [Any]()
var addTypeTicket = [String:Any]()
var imagesArray = [Any]()
var imagesFinal = [String:Any]()
let ticketDetails = ["ticketName":txtTicketName.text!,
"numberOfTicketOnSale":txtFldTotalQuantityofTicket.text!,
"ticketPrice":txtFldPriceofTicket.text!,
"messageForTicketBuyers":txtviewMessage.text!,
"ticketGroupName":txtFldGroupName.text!] as [String : Any]
ticketArray.append(ticketDetails)
print(ticketArray)
addTypeTicket["addTypeTicket"] = ticketArray
print(addTypeTicket)
viewShadowTicket.isHidden = true
viewForMainTicketAlert.isHidden = true
for alltickets in addTypeTicket {
let ticketName = (alltickets as AnyObject).object(forKey: "ticketName") as! String
let Quantity = (alltickets as AnyObject).object(forKey: "numberOfTicketOnSale") as! String
let ticketPrice = (alltickets as AnyObject).object(forKey: "ticketPrice") as! String
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: Quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
self.tableview.reloadData()
tableview.isHidden = false
I just want to get values in for loop .
If you are not using ticketArray anywhere else then there is not need to add data to that array. You can simply add data to addTypeTicket dictionary by:
addTypeTicket["addTypeTicket"] = ticketDetails
Then you can fetch the data like this:
if let addTypeTicketData = addTypeTicket["addTypeTicket"] as? [String: String] {
let ticketName = addTypeTicketData["ticketName"]
let quantity = addTypeTicketData["numberOfTicketOnSale"]
let ticketPrice = addTypeTicketData["ticketPrice"]
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
And use arrayTickets for tableView's numberOfRowsInSection.
I'm going to display some data from NSArray in the tableViewCell.
Here is my NSArray format
(
{
score = "480.0";
uid = 2;
},
{
score = "550.0";
uid = 1;
}
)
So, how to display for example score?
Here is m code, but it doesn't display it
var gamesRound: NSArray = []
let game = gamesRound[indexPath.row]
//let user = users[Int(game.userId - 1)]
cell.textLabel?.text = game as? String
//cell.detailTextLabel?.text = "\(String(Int(game.score))) PTS"
//print(user.fullname!)
return cell
Change your gamesRound variable to Array of Dictionary like this:
Put some value like this, in viewDidLoad (maybe):
var gamesRound = [[String: Any]]()
To render value on cells of a UITableView
gamesRound = [["score": "480.0", "uid" = 2], ["score": "550.0", "uid": 1]]
Some what like this:
let game = gamesRound[indexPath.row] as! [String: Any]
cell.textLabel?.text = "\(game["score"] as? Int ?? 0)"
cell.detailTextLabel?.text = "\(game["uid"] as? Int ?? 0)"
seems to me that you have an NSDictionary in each position of you NSArray.
So, use this code to get the position that you want:
let game = gamesRound[indexPath.row]
Now the game is an NSDictionary and you only need to extract the information using the key that you want:
let uid = game["uid"]
let score = game["score"]
I hope my example helps you.
Here you have the Array of dictionary so when you write let dict = gamesRound[indexPath.row] you will get the dictionary object and you can get the value by using the key because dictionary has the key value pair while the array has the indexing.
Also, you can Declare array like this
var gamesRound: Array<Dictionary<String,Any>> = []
So you can verify by printing the values step by step:
print(gamesRound)
let dict = gamesRound[indexPath.row] as! Dictionary<String,Any>
print(dict)
let score = dict["score"]
print(dict["score"])
cell.textLabel?.text = "\(score!)"
Try this code,
let gameRound : NSDictionary = yourArray[indexPath.row] as! NSDictionary
let strUid = gameRound["uid"]
cell.textLabel.text = strUid as? String
I have an array under another array and I want the value of the inner array and display them in UITextfield (eg : xyz,ABC,123) in iOS swift
let memberDetail = tobeReceivedArray[indexPath.row]["groupMembersVO"]
self.memberArray = memberDetail as! [AnyObject]
let amount = (tobeReceivedArray[indexPath.row]["totalPay"] as! Int) as NSNumber
let date = tobeReceivedArray[indexPath.row]["uploadOn"] as! String
let name = memberArray[indexPath.row]["name"] as! String
cell.amountLable.text = amount.stringValue cell.timeLable.text = date
cell.nameLable.text = name
You can simply use flat map for better understanding you can follow this link:
http://sketchytech.blogspot.in/2015/06/swift-what-do-map-and-flatmap-really-do.html
I want get the below json to my array for showing in UITableview
{
MyPets = (
{
breed = "";
breedvaccinationrecord = "";
"city_registration" = "";
"date_of_birth" = "";
"emergency_contacts" = "";
gender = m;
"pet_id" = 475;
"pet_name" = "IOS PET";
petinfo = "http://name/pet_images/";
"prop_name" = "";
"qr_tag" = 90909090;
species = Canine;
"vaccination_records" = "";
vaccinationrecord = "http://Name/vaccination_records/";
"vet_info" = "";
}
);
}
i am using below code to get values into array
if let dict = response.result.value {
print(response)
let petListArray = dict as! NSDictionary
self.petListArray = petListArray["MyPets"] as! [NSMutableArray]}
in cellForRowAtIndexPath i am using this line to display name in UILabel in TableCell
cell?.petName.text = self.petListArray[indexPath.row].valueForKey("pet_name") as? String
but it is crashing like
fatal error: NSArray element failed to match the Swift Array Element type
i am new to swift 2 please help me thanks in advance
First of all declare petListArray as Swift Array, do not use NSMutable... collection types in Swift at all.
By the way the naming ...ListArray is redundant, I recommend either petList or petArray or simply pets:
var pets = [[String:Any]]()
The root object is a dictionary and the value for key MyPets is an array, so cast
if let result = response.result.value as? [String:Any],
let myPets = result["MyPets"] as? [[String:Any]] {
self.pets = myPets
}
In cellForRow write
let pet = self.pets[indexPath.row]
cell?.petName.text = pet["pet_name"] as? String
It's highly recomenended to use a custom class or struct as model. That avoids a lot of type casting.
Why do I get an error when I used valueForKey... I am using same trick like in objectiveC ...
In ObjectiveC, the code is
self.strSubscribe =[responseObject[#"subscribe"] valueForKey:#"subscribe_ids"];
In Swift , the code is
self.strSubscribe = responseObject["subscribe"].valueForKey["subscribe_ids"] as! String
I declare the variables like
var arraySubCategory : NSMutableArray! = NSMutableArray()
var strSubscribe:String!
And I tried to access the value from below response
{
subscribe =
{
"subscribe_ids" = "1,14";
}
}
Edit
It works using Amit and Eric's solution but now for following data
{
data = (
{
"subscribe_ids" = "1,14";
}
);
}
let dictionary = responseObject["data"][0] as! Dictionary<String,AnyObject>
self.strSubscribe = dictionary["subscribe_ids"] as! String
OR//
if let dic = responseObject["data"][0] as? [String:String], let ids = dic["subscribe_ids"] {
self.strSubscribe = ids
}
but it gives me error:
could not find member 'subscript'
Swift doesn't know the type of responseObject["subscribe"], you have to help the compiler a bit; for example:
if let dic = responseObject["subscribe"] as? [String:String], let ids = dic["subscribe_ids"] {
self.strSubscribe = ids // "1,14"
}
UPDATE:
It's still the same problem: the compiler doesn't know the type of responseObject["data"], so when you try to access the subscript there's an error (because you know it's a dictionary inside the array, but the compiler doesn't).
One solution is to give the type to the compiler by declaring an array of dictionaries in the if let condition:
if let arr = responseObject["data"] as? [[String:String]], let ids = arr[0]["subscribe_ids"] {
self.strSubscribe = ids
}
Notice that it's [[String:String]] (array of dictionaries), not [String:String] (dictionary).
Write like this.
let dictionary = responseObject["subscribe"] as! Dictionary<String, AnyObject>
self.strSubscribe = dictionary["subscribe_ids"] as! String
Since responseObject["subscribe"] will give a AnyObject? output and AnyObject does not have any member called valueForKey.