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] }
Related
I want to create array of array
ex-
let myImages: [[String]] = [
["image_url_0_0", "image_url_0_1", "image_url_0_2", "image_url_0_3"],
["image_url_1_0", "image_url_1_1", "image_url_1_2"],
["image_url_2_0", "image_url_2_1", "image_url_2_2", "image_url_2_3", "image_url_2_4"]
]
I tried this, but it doesn't work perfectly.
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
But I get result in this form
[["image_url_0_0"], ["image_url_0_0","image_url_0_1"], ["image_url_0_0","image_url_0_1","image_url_0_3"].....]
How should I do this?Please Help.
You try this
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
let arr : [String] = []
for customParams in custom_attributes! {
if(customParams["attribute_code"] as! String == "small_image")
{
print(customParams["value"])
var myString = customParams["value"] as! String
arr.append(myString)
}
}
myArray.append(arr)
}
First you need to create simple string array and then append this array to your myArray. Check following code may be it's help
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
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)
How can I filter these json object? I mean I want print only patients whose id is equal to 3.
var patients: Array<AnyObject>? if let obj: AnyObject = manager?.responseObject as AnyObject? {
if let pats = obj["patients"] as! Array<AnyObject>? {
patients = pats
}
}
This is my printed variable
{
patients = (
{
city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
firstname = fdfsdf;
lastname = dsfgsdfg;
"patient_id" = 1064;
"patient_status" = 3;
"register_id" = "\U0430\U043083040411";
}
{
city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
firstname = dwfw;
lastname = dsfsdf;
"patient_id" = 1056;
"patient_status" = 1;
"register_id" = "\U0443\U044399111134";
}
}
Please cast the types down as much as possible.
All types are more specific than AnyObject, JSON dictionaries are always [String:AnyObject] and JSON arrays are Array<[String:AnyObject]>. Use Array<AnyObject> only if the array contains another array or is more nested.
Filter the patients with the filter function.
var patients = Array<[String:AnyObject]>()
if let obj = manager?.responseObject as? [String:AnyObject] {
if let pats = obj["patients"] as? Array<[String:AnyObject]> {
patients = pats.filter { $0["patient_status"] as! Int == 3 }
}
}
Note: In Swift 3 AnyObject has been replaced with Any.
please, ask me, where is my mistake? I have Xcode error:
Cannot subscript a value of type '[Int : [String]]' with an index of
type 'String!'
in let keyExists = myDict[tmp.Hour] != nil, myDict[tmp.Hour] = Int and myDict[tmp.Hour].append(tmp.Minutes) of that part of code:
func array() -> Dictionary <Int,[String]>
{
let timeInfos = getTimeForEachBusStop()
var myDict: Dictionary = [Int:[String]]()
for tmp in timeInfos {
let keyExists = myDict[tmp.Hour] != nil
if (!keyExists) {
myDict[tmp.Hour] = [Int]()
}
myDict[tmp.Hour].append(tmp.Minutes)
}
return myDict
}
I understand, that problem is in optional type, but where is problem I don't understand
upd
func getTimeForEachBusStop() -> NSMutableArray {
sharedInstance.database!.open()
let lineId = getIdRoute
let position = getSelectedBusStop.row + 1
let getTimeBusStop: FMResultSet! = sharedInstance.database!.executeQuery("SELECT one.hour, one.minute FROM shedule AS one JOIN routetobusstop AS two ON one.busStop_id = (SELECT two.busStop_id WHERE two.line_id = ? AND two.position = ?) AND one.day = 1 AND one.line_id = ? ORDER BY one.position ASC ", withArgumentsInArray: [lineId, position, lineId])
let getBusStopInfo : NSMutableArray = NSMutableArray()
while getTimeBusStop.next() {
let stopInfo: TimeInfo = TimeInfo()
stopInfo.Hour = getTimeBusStop.stringForColumnIndex(0)
stopInfo.Minutes = getTimeBusStop.stringForColumnIndex(1)
getBusStopInfo.addObject(stopInfo)
}
sharedInstance.database!.close()
return getBusStopInfo
}
You are declaring your dictionary as a dictionary with keys of type Int and values of type [String]:
var myDict: Dictionary = [Int:[String]]()
(better written as: var myDict: [Int: [String]] = [:] because by casting it to Dictionary you are removing the types).
However, in
myDict[tmp.Hour] = [Int]()
You are using a value which is of [Int] type and tmp.Hour is probably a String.
So, your problem is a type mismatch.
The error states that you cannot subscribe your [Int:[String]] dictionary with a String key.
Therefore the type of tmp.Hour is obviously String rather than the expected Int
If tmp.Hour is guaranteed to be an integer string you can convert the value
let hour = Int(tmp.Hour)!
myDict[hour] = [Int]()
On the other hand since myDict is [Int:[String]] you might mean
let hour = Int(tmp.Hour)!
myDict[hour] = [String]()
Hour and Minutes are of type string (I guess - stringForColumnIndex) so your dictionary is wrong type. Should be:
func array() -> Dictionary <String,[String]>
{
let timeInfos = getTimeForEachBusStop()
var myDict: Dictionary = [String:[String]]()
for tmp in timeInfos {
let keyExists = myDict[tmp.Hour] != nil
if (!keyExists) {
myDict[tmp.Hour] = [String]()
}
myDict[tmp.Hour].append(tmp.Minutes)
}
return myDict
}
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)
}
}
}