this is my dictionary value
var dict: NSDictionary = NSDictionary()
dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary
print(dict as Any)
{
cityId = 1;
cityName = Dammam;
countryId = 1;
mobile = 123;
name = "My name";
}
now i have to update cityid = "2", mobile = "456", name = "othername"
and create same as above Dictionary with updated values.
help me with this.
Modify your code as below
var dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! Dictionary<String,Any>
dict["cityid"] = "2"
dict["mobile"] = "456"
dic["name"] = "other name"
you are forcefully unwraping the dictionary it is not recommended ..
You can not update value in NSDictionary, so you have to use NSMutableDictionary.
var dict: NSMutableDictionary = NSMutableDictionary()
dict = (pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary).mutableCopy() as! NSMutableDictionary
dict["cityId"] = 2
dict["mobile"] = 456
dict["name"] = "othername"
print(dict)
Related
I am using Swift 3.
I am getting the following response from a server and i need to parse and get values such as, Account No, Account Type, Address etc.
parsedData: (
{
key = "<null>";
offset = 1;
partition = 0;
topic = test;
value = {
"Account No" = 675;
"Account Type" = Saving;
Address = location;
User ID = 601;
User Name = Stella;
};
}
)
I have been trying to get value first, and then planning to get each value,
var temp: NSArray = parsedData["value"] as! NSArray
but this is giving error as cannot convert value of type String to expected argument type Int.'
How to retrieve values from the above mentioned array?
parsedData is an array which contains Dictionary at first index.
let dicData = parsedData[0] as! Dictionary
let valueDictionary = dicData["value"] as! Dictionary //dicData also contains dictionary for key `value`
let accountNumber = valueDictionary ["Account No"] //**Account number**
//////SECOND APPROACH IF YOU HAVE DICTIONARY IN RESPONSE
var valueDictionary : NSDictionary = parsedData["value"] as? NSDictionary
let accountNumber = valueDictionary ["Account No"] //**Account number**
You parse a dictionary as an array
var temp: NSDictionary = parsedData["value"] as? NSDictionary
Try this
let dicData = parsedData[0] as! Dictionary
var temp: NSDictionary = dicData["value"] as? NSDictionary
let accountNumber = temp.object(forKey: "Account No")
let accountType = temp.object(forKey: "Account Type")
let address = temp.object(forKey: "Address")
let userID = temp.object(forKey: "User ID")
let userName = temp.object(forKey: "User Name")
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.
I have array of dictionary, I am trying to store it in NSuserdefault but as it contain <null> app get crash, can we replace <null> with ""?
Is there any way to resolve this issue?
This is my array of dictionaries:
var array = (
{
ClinicID = "<null>";
"Patient_SurveyID" = 1956;
"Patient_Treatment_PlanID" = "<null>";
PhysicianID = "<null>";
},
{
ClinicID = "<null>";
"Patient_SurveyID" = 1956;
"Patient_Treatment_PlanID" = "<null>";
PhysicianID = "<null>";
},
)
So you have an array of dictionaries
let list: [[String:Any]] = []
and each dictionary is of type [String:Any].
This is the code to replace the NSNull values into your dictionaries with
""
let list: [[String:Any] = []
let updatedDict = list.map { (dict) -> [String:Any] in
let keysWithEmptStringValue = dict.filter { $0.1 is NSNull }.map { $0.0 }
var dict = dict
for key in keysWithEmptStringValue {
dict[key] = ""
}
return dict
}
From NSMutableArray to [[String:Any]]
To convert your NSMutableArray to a Swift generic array please try this code
let array = NSMutableArray()
let list: [[String:Any]] = array.flatMap { $0 as? [String:Any] }
I have stored my contacts as a dictionary on an mutable array by this method:
var addressBookReff: ABAddressBookRef = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
var arrOfDictContacts:NSMutableArray = NSMutableArray()
let people:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBookReff).takeRetainedValue()
for person in people{
if let name:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String {
arrOfDictContacts.addObject(["\(name)":"\(number)"])
}
}
}
Here, arrOfDictContacts is my mutable array which contains name and number as dictionary. Like this :
arrOfDictContacts = ({ my = 12131;}, { doctor = 54445;}, { AL = 543212601;}, { customer = 121; } }
Now I have another array of names as
arrOfNames = [my, AL]
I want to get the respective numbers of the arrOfNames from arrOfDictContacts
ExpectedOutput :
arrOfNumbers = [12131, 543212601]
How can I do this?
Edit:
Since your array contains dictionaries, the way to do it is to check each of the dictionaries against your array. Like following:
var arrOfNumbers : [String] = []
for dict in arrOfDictContacts {
for name in arrOfNames {
if let value = dict[name] as? String {
arrOfNumbers.append(value)
}
}
}