How to search an element in Array of Dictionary? - ios

Below mentioned is my array. I need to check if the barcode 8901058847857 or barcode xxxxxxxxxxx exists in array or not.
(
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
I tried using array.contains or array.elements but it is not working because barcode exists in an array.

** Try this **
// Put your key in predicate that is "barcode"
var namePredicate = NSPredicate(format: "barcode contains[c] %#",searchString);
let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) };
print("names = ,\(filteredArray)")

You can search your array of dictionaries using contains where but you need to cast your value from Any to Int before trying to compare them:
if array.contains(where: {$0["barcode"] as? Int ?? 0 == 8901058847857}) {
print(true)
}

You can also run for loop to check the presence of element in your Array of dictionary.
let DictnaryArray = (
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
for (index,element) in DictnaryArray{
let dict = DictnaryArray[index]
if dict["barcode"] == 8901058847857 || dict["barcode"] == XXXXXXXXXXX{
print("BarCode Exist")
print("\(dict["barcode"])")
}
}
Hope it helps!

Related

Traverse nsdictionary in swift

I am new to swift.
I have my dictionary as
monthData =
{
"2018-08-10" = {
accuracy = 71;
attempted = 7;
correct = 5;
reward = Bronze;
};
"2018-08-12" = {
accuracy = 13;
attempted = 15;
correct = 2;
reward = "";
};
"2018-08-13" = {
accuracy = 33;
attempted = 15;
correct = 5;
reward = "";
};
"2018-08-14" = {
accuracy = 100;
attempted = 15;
correct = 15;
reward = Gold;
};
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
"2018-08-21" = {
accuracy = 26;
attempted = 15;
correct = 4;
reward = "";
};
"2018-08-23" = {
accuracy = 46;
attempted = 15;
correct = 7;
reward = "";
};
}
I want to get all the dates for which reward is Gold
Can anyone please help me do that?
What I have tried 'till now is:
for (key,value) in monthData{
let temp = monthData.value(forKey: key as! String) as! NSDictionary
for (key1,value1) in temp{
if((value1 as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
but it outputs the error Could not cast value of type '__NSCFNumber' to 'NSString'
The error occurs because when you are iterating the dictionary you force cast the Int values to String which is not possible
The (highly) recommended Swift way is to use the filter function. This is much more efficient than a loop.
In the closure $0.1 represents the value of the current dictionary ($0.0 would be the key). The result is an array of the date strings.
let data : [String:Any] = ["monthData" : ["2018-08-10": ["accuracy" : 71, "attempted" ... ]]]
if let monthData = data["monthData"] as? [String:[String:Any]] {
let goldData = monthData.filter { $0.1["reward"] as? String == "Gold" }
let allDates = Array(goldData.keys)
print(allDates)
}
The code safely unwraps all optionals.
However if there is only one Gold entry the first function is still more efficient than filter
if let monthData = data["monthData"] as? [String:[String : Any]] {
if let goldData = monthData.first( where: {$0.1["reward"] as? String == "Gold" }) {
let goldDate = goldData.key
print(goldDate)
}
}
In Swift avoid the ObjC runtime (value(forKey:)) and Foundation collection types (NSDictionary) as much as possible.
From the first for in loop, you are getting the NSDictionary in temp variable
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
So, you should directly check .value(forKey:) on temp and get the value for reward.
You should try it like this
for (key,value) in monthData {
let temp = monthData.value(forKey: key as! String) as! NSDictionary
if(((temp.value(forKey: "reward")) as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
Try and share results
EDIT
Please checkout the answer from vadian for in-depth explanation and pure swift approach to achieve the same.
Thanks

Swift Query Request crashing when value is null

Query results retrieved
"Adjusted_Lease_Value__c" = "0.0";
"Amount_Financed__c" = "23520.64";
"Assignment_Amount__c" = "19220.21";
"Category__c" = 4;
"Charge_Off_Amount__c" = "0.0";
"Committed_Funds__c" = "19220.21";
"Date_Assigned_Back_to_ACG__c" = "<null>"
How I'm retrieving them:
// Initial Access to Salesforce in order to query data
client.performLogin(accessUsername, password: accessPassword, fail:{ (fail) in
}) { (success) in
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
// This line fails
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as! String
// This works no problem
let AmountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as! String
}
When the query result is "null" it crashes the app. What should I do?
If it may nil then do not use forced conversion.
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as? String
let amountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as? String
}

How Parse JSON from API [duplicate]

This question already has answers here:
type 'Any' has no subscript members
(2 answers)
Closed 5 years ago.
i know to much ask like this. i already searching but not match with my problems.
oke i will try explain with my code
i have data API Like this
["profile": {
accountId = 58e470a0c50472851060d083;
androidDeviceId = "[\"3453247ddcf3f809\"]";
androidVersion = 21;
appId = (
"c46b4c10-62ce-11e6-bdd4-59e4df4b8410",
"fac915f0-fe2b-11e6-9dfb-55339bd7be35"
);
appVersion = "v5.1.0";
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg";
birthDate = "12/03/1994";
"channel-group" = android;
communityId = 553e09b251906884443eff85;
coordinates = {
coordinates = (
"106.9602383333333",
"-6.249333333333334"
);
type = Point;
};
crop = "";
crops = "<null>";
customerId = 5369bd85cae84d0e03246a7c;
dateSubmitted = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
fullName = "Megi Fernanda";
gender = "Laki-laki";
homeAddress = Payakumbuah;
location = "Kota Payakumbuh";
moderation = {
at = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
by = auto;
status = moderated;
};
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
type = users;
university = "Politeknik Negeri Pertanian Payakumbuh";
}, "accessToken": {
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0.";
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo.";
}]
i already can got fullName, Addres, Skill State etc
if let profile = json["profile"] as? NSDictionary {
let name = profile["fullName"]
let alamat = profile["Skill"]
}
but i don't know how to get atribut in totalConversation like question, storeItems, points
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
i tried like
let profile = json["profile"]["totalConversation"] as? NSDictionary
error sign : Type 'any?' has no subscript members
You got that error because json["profile"] is Any type and it doesn't have any subscript. So you need to cast json["profile"] to a dictionary, [String: Any] is dictionary type in Swift.
if let profile = json["profile"] as? [String: Any] {
if let totalConversations = profile["totalConversations"] as? [String: Any] {
let questions = totalConversations["questions"] as? Int
}
}

How to index into Array of Dictionaries

I have an object that looks like this in the console. It seems like an array with a dictionary inside. How can I get to the address field?
Optional((
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
))
The object comes from this object:
<METDocument key: <collection: users, ID: KTsCySacEAiz3eDnf>, fields: {
emails = (
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = Oslo;
country = nor;
lineOne = "address";
lineTwo = "";
zip = 0264;
};
birthdate = "1985-09-01 23:00:00 +0000";
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
gender = Male;
name = {
first = "Elon";
last = "Musk";
};
phone = 911;
validated = 1;
};
}>
I access the emails key by this method:
let emails = users.allDocuments[0].valueForKey("emails")
The content of the object is an optional array.
There are two options:
Safe access:
if let emails = users.allDocuments[0].objectForKey("emails") where emails.count > 0 {
if let address = emails[0]["address"] as? String {
print(address)
}
}
If it's guaranteed that the dictionary in the array and the key address exists:
let emails = users.allDocuments[0].objectForKey("emails")!
let address = emails[0]["address"] as! String

NSDictionary annidate in swift

I have this json result.
I would take the field "alert".
I try this:
var alert: NSString = jsonResult["features"]["properties"]["alert"]
but this is the error: does not have a member named 'subscript'.
I can not how to access a field in a nested dictionary
{
features = (
{
geometry = {
coordinates = (
"-97.95359999999999",
"37.2382",
5
);
type = Point;
};
id = usb000si7g;
properties = {
alert = green;
cdi = "5.8";
code = b000si7g;
detail = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/usb000si7g.geojson";
dmin = "0.017";
felt = 1258;
gap = 38;
ids = ",usb000si7g,";
mag = "4.3";
magType = mwr;
mmi = "4.94";
net = us;
nst = "<null>";
place = "8km SE of Harper, Kansas";
rms = "0.51";
sig = 864;
sources = ",us,";
status = reviewed;
time = 1412272884590;
title = "M 4.3 - 8km SE of Harper, Kansas";
tsunami = "<null>";
type = earthquake;
types = ",cap,dyfi,general-link,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,";
tz = "-300";
updated = 1412614943519;
url = "http://earthquake.usgs.gov/earthquakes/eventpage/usb000si7g";
};
type = Feature;
}
);
metadata = {
api = "1.0.13";
count = 1;
generated = 1412617232000;
status = 200;
title = "USGS Significant Earthquakes, Past Week";
url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson";
};
type = FeatureCollection;
}
I don't know what to do. swift is changed every beta.
As #Kirsteins said is his answer, you have to do a lot of unwrapping, and it's recommended to use a JSON library.
If you still want to stick with hand made extraction, then I suggest you to made it programmatically, such as adding an extension to NSDictionary as follows:
extension NSDictionary {
func objectForTreeKeys<T>(keys:[String]) -> T? {
var dict: NSDictionary? = self
var retValue: T?
for key in keys {
var value: AnyObject? = dict?.objectForKey(key)
if let unwrapped = value as? NSDictionary {
dict = unwrapped
} else if let unwrapped = value as? T {
retValue = unwrapped
break
} else {
retValue = nil
break
}
}
return retValue
}
}
You pass an array of keys to the function, and it traverses all nested dictionaries until:
a value of type T is encountered
a value having type different than NSDictionary and T is found
a nil value is found
In the first case, it returns the value of T type - in the other cases it returns nil.
You can use it as follows:
let ret: String? = jsonResult.objectForTreeKeys(["features", "properties", "alert"])
As you can see, it's a generic method, and the return type is inferred from the type of the variable the result is assigned to - so it's necessary to explicitly define its type, which must be optional (String? in this specific case).

Resources