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
Related
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
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 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.
In the following snippet of code I am retrieving some Int values from an API call.
I want to use these values to update a couple of UILables on my app.
if let dict = json?["Stats"] as? [String:AnyObject] {
self.tempTotalWins = [dict["totalWins"]! as! Int]
self.tempTotalDraws = [dict["totalDraws"]! as! Int]
self.totalWins = String(describing: self.tempTotalWins)
self.totalDraws = String(describing: self.tempTotalDraws)
print (self.tempTotalWins)
self.wonLabel.text = self.totalWins!
self.drawnLabel.text = self.totalDraws!
}
This is currently outputting and updating the labels as [1] and [3].
How do I remove the [ ] so it just prints the number 1 and 3?
The square brackets is noted as Array and that is created by you, in this line [dict["totalWins"]! as! Int] you have initialized self.tempTotalWins as array of Int. If you want only first object then you can get it like this.
if let total_Wins = dict["totalWins"] as? Int, let total_Draws = dict["totalDraws"] as? Int
self.totalWins = String(total_Wins)
self.totalDraws = String(total_Draws)
}
I'm having a lot of frustration with Swift when it comes to working with Dictionaries and NSDictionaries.
I am pulling data from a server. One of the values is a Bool.
I started with a Swift Dictionary and moved to NSDictionary out of frustration. However, I still cannot get the values from the dictionary.
All of the following fail with contradictory errors:
let unread:Bool = data!["unread"] as! Bool
let unread:Bool = data?["unread"] as! Bool
let unread:Bool = data?.objectForKey("unread") as! Bool
let unread:NSNumber = data?["unread"] as! NSNumber
error: Could not cast value of type 'NSTaggedPointerString' (0x110c1eae8) to 'NSNumber' (0x10e0ab2a0).
Okay, looks like that data is coming in as a String... let's try:
let unreadStr:String = data!["unread"] as! String
let unreadStr:NSString = data!["unread"] as! NSString
error: Could not cast value of type '__NSCFBoolean' (0x1097413b8) to 'NSString' (0x106bcdb48).
So I'm confused. When I try to convert it to a Bool it says I cannot convert a String to a Number. When I try to convert it to a String, it says I cannot convert a number to a string.
Here is what the data looks like:
Optional({
senderId = 10154040;
sent = 1460844986973;
text = "Test Message 1";
unread = false;
})
You should try something along these lines:
let data: [String : Any] = ["first" : "test", "second" : 2, "third" : true]
let first = data["first"] as! String
let second = data["second"] as! Int
let third = data["third"] as! Bool
print(first)
print(second)
print(third)