parsed is an NsDictionary and I am pulling the balances out of it via
if let findbalances: AnyObject = parsed["balances"]
which gives me a list of balances in AnyObject format
(
{
"available_amount" = 133519;
currency = AUD;
},
{
"available_amount" = 7854;
currency = CAD;
},
{
"available_amount" = 88581;
currency = EUR;
},
{
"available_amount" = 0;
currency = GBP;
},
{
"available_amount" = 63618;
currency = INR;
},
{
"available_amount" = 375;
currency = NZD;
},
{
"available_amount" = 0;
currency = TRY;
},
{
"available_amount" = 2918958;
currency = USD;
}
)
I know that
let whatCurrency = (findbalances[7]["currency"] as! String)
=USD But how do I find that value [7] if the amount of objects changes?
I want to match on USD
I tried
let defaultcurr = "USD"
let findUSD = findbalances.indexOfObject(defaultcurr)
but that gave me 9223372036854775807
How do I just find 7
9223372036854775807 is NSNotFound.
You can use a closure as argument of indexOf
let defaultcurr = "USD"
let findUSDIndex = findbalances.indexOf { ($0["currency"] as! String) == defaultcurr }
Or you can filter the entire row
let findUSD = findbalances.filter { ($0["currency"] as! String) == defaultcurr }.first
indexOfObject seems to be using NSArray. Don't do that. Use Swift native Array and cast your collection object to [[String:AnyObject]] :
if let findbalances = parsed["balances"] as? [[String:AnyObject]] { ...
Related
I'm facing this strange problem. I have to parse this json and extract "symbol","High","low" and "direction". this is the original json
[{"ID":101,"Symbol":"PKR","Bid":105.7,"Ask":106,"High":105.7,"Low":106,"Change":0,"Direction":"0","CreateDate":"04:38:26","EntityState":2,
"EntityKey":{"EntitySetName":"v_openmarketrates","EntityContainerName":"tradebizEntities",
"EntityKeyValues":[{"Key":"ID","Value":101}],
"IsTemporary":false}},
{"ID":1,"Symbol":"EUR","Bid":126.696,"Ask":127.327,"High":126.7622,"Low":126.9752,"Change":0.4192,"Direction":"0","CreateDate":"06:37:31","EntityState":2,
"EntityKey":{"EntitySetName":"v_openmarketrates","EntityContainerName":"tradebizEntities","EntityKeyValues":[{"Key":"ID","Value":1}],
"IsTemporary":false}}]
When i'm parsing this in json, it is fetching all the values correctly except the value of "Direction",like this:
[{
Ask = 106;
Bid = "105.7";
Change = 0;
CreateDate = "04:38:26";
Direction = 0;
EntityKey = {
EntityContainerName = tradebizEntities;
EntityKeyValues = (
{
Key = ID;
Value = 101;
}
);
EntitySetName = "v_openmarketrates";
IsTemporary = 0;
};
EntityState = 2;
High = "105.7";
ID = 101;
Low = 106;
Symbol = PKR;
},
{
Ask = "127.265";
Bid = "126.623";
Change = "0.3463";
CreateDate = "06:30:46";
Direction = 0;
EntityKey = {
EntityContainerName = tradebizEntities;
EntityKeyValues = (
{
Key = ID;
Value = 1;
}
);
EntitySetName = "v_openmarketrates";
IsTemporary = 0;
};
EntityState = 2;
High = "126.7306";
ID = 1;
Low = "126.9752";
Symbol = EUR;
}
i have no idea how the value inside json is getting changed while parsing even though rest of the values are correct. this is how i'm parsing it.
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? [NSDictionary] {
print("kerb rates full json = ",jsonResult )
for field in jsonResult as? [AnyObject] ?? [] {
print("fields of kerb rates = \(field)")
print("kerb directions \((field["Direction"] as? String)!)")
let subfield : AnyObject = (field["EntityKey"] as? AnyObject)!
let sub_subfield : AnyObject = (subfield["EntityKeyValues"] as? AnyObject)!
print("sub_subfield = \(sub_subfield)")
print("subfields = \(subfield)")
// for key_Subfield in sub_subfield as? [AnyObject] ?? [] {
print("inside loop!")
// converting int and bool values
let ask = (field["Ask"] as? Int)!
let bid = (field["Bid"] as? Int)!
let change = (field["Change"] as? Int)!
let EntityState = (field["EntityState"] as? Int)!
let High = (field["High"] as? Double)!
let ID = (field["ID"] as? Int)!
let IsTemporary = ""//(subfield["IsTemporary"] as? Bool)!
let Low = (field["Low"] as? Double)!
let Value = ""//(key_Subfield["Value"] as? Int)!
// it is crashing here due to multple dictionaries
self.Save_KerbRates(ask: (String(ask)),
bid: (String(bid)),
change: (String(change)),
createDate: (field["CreateDate"] as? String)!,
direction: (field["Direction"] as? String)!,
entityContainerName: "",//(subfield["EntityContainerName"] as? String)!,
entitiySetName:"",// (subfield["EntitySetName"] as? String)!,
entitiyState: (String(EntityState)),
high: (String(High)),
id: (String(ID)),
isTemporary: (String(IsTemporary)),
key:"",// (key_Subfield["Key"] as? String)!,
low: (String(Low)),
symbol: (field["Symbol"] as? String)!,
value: (String(Value)))
// }
}
Update:
After using [[String:Any]]
i'm still getting the wrong value of direction,like this
kerb rates full json = [["Low": 106, "Direction": 0, "EntityState": 2, "EntityKey": {
EntityContainerName = tradebizEntities;
EntityKeyValues = (
{
Key = ID;
Value = 101;
}
);
EntitySetName = "v_openmarketrates";
IsTemporary = 0;
}, "ID": 101, "CreateDate": 04:38:26, "Symbol": PKR, "Change": 0, "Ask": 106, "High": 105.7, "Bid": 105.7], ["Low": 126.9752, "Direction": -1, "EntityState": 2, "EntityKey": {
EntityContainerName = tradebizEntities;
EntityKeyValues = (
{
Key = ID;
Value = 1;
}
);
EntitySetName = "v_openmarketrates";
IsTemporary = 0;
}, "ID": 1, "CreateDate": 07:03:46, "Symbol": EUR, "Change": 0.4403, "Ask": 127.349, "High": 126.7654, "Bid": 126.717],
This parses (and prints) all values in the first level of the dictionary and the value for keys IsTemporary and Value in the second level. All variable names start with a lowercase letter to conform to the naming convention.
The code uses a type alias for convenience.
Be aware that the code does not use any error handling to check the dictionary keys. If it is not guaranteed that all items contain all keys and values you have to use optional bindings.
typealias JSONDictionary = [String:Any]
do {
if let jsonResult = try JSONSerialization.jsonObject(with:data!) as? [JSONDictionary] {
for field in jsonResult {
let ask = field["Ask"] as! Double
let bid = field["Bid"] as! Double
let change = field["Change"] as! Double
let createDate = field["CreateDate"] as! String
let direction = field["Direction"] as! String
let entityState = field["EntityState"] as! Int
let high = field["High"] as! Double
let id = field["ID"] as! Int
let low = field["Low"] as! Double
let symbol = field["Symbol"] as! String
let entityKey = field["EntityKey"] as! JSONDictionary
let isTemporary = entityKey["IsTemporary"] as! Bool
let entityKeyValues = entityKey["EntityKeyValues"] as! [JSONDictionary]
let value = entityKeyValues[0]["Value"] as! Int
print(ask, bid, change, createDate, direction, entityState, high, id, low, symbol, isTemporary, value)
}
}
} catch {
print(error)
}
I would like to check the value of the outgoing variable whether it is 0 or 1. I tried below code to do the same but I am not able to check it. In below code message is a dictionary which contains values of XMPPMessageArchiving_Message_CoreDataObject.
How to check the value of outgoing variable?
message dictionary contains:
bareJid = "(...not nil..)";
bareJidStr = "tester3#90.0.0.163";
body = "{\"Date\":\"14 Jun 2017\",\"Time\":\"4:21PM\",\"body\":\"hello\",\"filePath\":\"\",\"isImportant\":\"N\",\"isMine\":true,\"msgid\":\"167-36\",\"receiver\":\"tester1\",\"sender\":\"tester3\",\"senderName\":\"tester3\"}";
composing = 0;
message = "(...not nil..)";
messageStr = "<message xmlns=\"jabber:client\" to=\"tester1#90.0.0.163\" id=\"167-36\" type=\"chat\" from=\"tester3#90.0.0.163/Smack\"><body>{\"Date\":\"14 Jun 2017\",\"Time\":\"4:21PM\",\"body\":\"hello\",\"filePath\":\"\",\"isImportant\":\"N";
outgoing = 0;
streamBareJidStr = "tester1#90.0.0.163";
thread = "2066797c-4f79-48f3-bd04-30658ee35e9f";
timestamp = "2017-06-14 11:20:41 +0000";
When I debug the value of outgoing variable then Xcode shows the type of it is Any? and value of it is some.
let outgoing = messasge.value(forKey: "outgoing")
var isIncoming = true
if let og = outgoing as? Int {
if og == 1 {
isIncoming = false
}
}
If your dictionary value data type is Anyobject then unwrap as NSNumber and convert to integer or bool
if let outgoing = message["outgoing"] {
let convertedValue = Int(outgoing as! NSNumber)
if convertedValue == 1 {
isIncoming = false
print("Incoming false")
}
}
Example :
var messasge = [String: AnyObject]()
messasge["outgoing"] = "1" as AnyObject;
if let outgoing = messasge["outgoing"] {
let convertedValue = Int(outgoing as! NSNumber)
if convertedValue == 1 {
print("Incoming false")
}
}
message["outgoing"] value data type is String :
var messasge = [String: Any]()
messasge["outgoing"] = "1" ;
if let outgoing = messasge["outgoing"] as? String, outgoing == "1" {
isIncoming = false
}
message["outgoing"] value data type is Int :
var messasge = [String: Any]()
messasge["outgoing"] = 1 ;
if let outgoing = messasge["outgoing"] as? Int, outgoing == 1 {
isIncoming = false
}
let outgoing : String = messasge.value(forKey: "outgoing")
let og = Int(outgoing)
if og == 1
{// isIncoming = false
}
else
{
//isIncoming = true
}
I am trying to sort an array of anyobject, but not able to do it.I get some data from Parse database in AnyObject format. As per below data, I want to sort this AnyObject array by "NAME". Below is my code -
let sortedArray = (myArray as! [AnyObject]).sorted(by: { (dictOne, dictTwo) -> Bool in
let d1 = dictOne["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"
let d2 = dictTwo["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"
return d1 < d2
})
myArray looks like this -
{
LINK = "www.xxx.com";
MENU = Role;
"MENU_ID" = 1;
NAME = "A Name";
SUBMENU = "XXX";
"Training_ID" = 2;
},
{
LINK = "www.xyz.com";
MENU = Role;
"MENU_ID" = 2;
NAME = "B name";
SUBMENU = "jhjh";
"Training_ID" = 6;
},
{
LINK = "www.hhh.com";
MENU = Role;
"MENU_ID" = 3;
NAME = "T name";
SUBMENU = "kasha";
"Training_ID" = 7;
},
{
LINK = "www.kadjk.com";
MENU = Role;
"MENU_ID" = 5;
NAME = "V name";
SUBMENU = "ksdj";
"Training_ID" = 1;
},
{
LINK = "www.ggg.com";
MENU = Role;
"MENU_ID" = 4;
NAME = "K name";
SUBMENU = "idiot";
"Training_ID" = 8;
},
{
LINK = "www.kkk.com";
MENU = Role;
"MENU_ID" = 6;
NAME = "s name";
SUBMENU = "BOM/ABOM/BSM";
"Training_ID" = 12;
}
Any help would be much appreciated. Thanks!
It's not [AnyObject] (array of I-have-no-idea), it's array of dictionaries [[String:Any]]. Be more specific, this resolves the error.
In Swift 3 the compiler must know the specific type of all subscripted objects.
let sortedArray = (myArray as! [[String:Any]]).sorted(by: { (dictOne, dictTwo) -> Bool in
let d1 = dictOne["NAME"]! as String
let d2 = dictTwo["NAME"]! as String
return d1 < d2
})
Why are converting array to [AnyObject] instead of that convert the array to the [[String:Any]] means Array of Dictionary and tell the compiler that array contains Dictionary as objects.
if let array = myArray as? [[String:Any]] {
let sortedArray = array.sorted(by: { $0["NAME"] as! String < $1["NAME"] as! String })
}
Note: As of you are having NAME key with String value in your each dictionaries of array I have force wrapped it with the subscript.
You can use below function if you want
//function to sort requests
func sortRequests(dataToSort: [[String:Any]]) -> [[String:Any]] {
print("i am sorting the requests...")
var returnData = [[String:Any]]()
returnData = dataToSort
returnData.sort{
let created_date0 = $0["date"] as? Double ?? 0.0
let created_date1 = $1["date"] as? Double ?? 0.0
return created_date0 > created_date1
}
return returnData
}
I have a dict(NSDictionary) that has the following data.
{
images = (
{
image = "image.jpg";
scores = (
{
"classifier_id" = "Adventure_Sport";
name = "Adventure_Sport";
score = "0.662678";
},
{
"classifier_id" = Climbing;
name = Climbing;
score = "0.639987";
},
{
"classifier_id" = Flower;
name = Flower;
score = "0.628092";
},
{
"classifier_id" = "Nature_Scene";
name = "Nature_Scene";
score = "0.627548";
},
{
"classifier_id" = Icicles;
name = Icicles;
score = "0.617094";
},
{
"classifier_id" = Volcano;
name = Volcano;
score = "0.604928";
},
{
"classifier_id" = Potatoes;
name = Potatoes;
score = "0.602799";
},
{
"classifier_id" = "Engine_Room";
name = "Engine_Room";
score = "0.595812";
},
{
"classifier_id" = Bobsledding;
name = Bobsledding;
score = "0.592521";
},
{
"classifier_id" = White;
name = White;
score = "0.587923";
},
{
"classifier_id" = Yellow;
name = Yellow;
score = "0.574398";
},
{
"classifier_id" = "Natural_Activity";
name = "Natural_Activity";
score = "0.54574";
},
{
"classifier_id" = Butterfly;
name = Butterfly;
score = "0.526803";
},
{
"classifier_id" = "Dish_Washer";
name = "Dish_Washer";
score = "0.513662";
},
{
"classifier_id" = Rainbow;
name = Rainbow;
score = "0.511032";
}
);
}
);
}
I am not able to figure out a way to access classfier_id in an array
Really need your help. Thanks. PS I have already tried dict["scores"] and dict["image.scores"]
Kindly help.. Thanks
You want
let classifier_ids = dict["scores"].map{$0["classifier_id"]}
If your containers are NSObjects rather than Swift Dictionaries and Arrays then you will need to add some type-casting, but that's the basic idea.
This code would be safer for non-typed collections:
var classifier_ids: [String?]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.map{$0["classifier_id"]}
}
That should give you an array of optionals, where a given entry will be nil if that entry in the array did not contain a "classifier_id" key/value pair.
Or if you want to skip entries that don't contain a "classifier_id" key/value pair:
var classifier_ids: [String]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.flatmap{$0["classifier_id"]}
}
Taking it a step at at time:
if let array = dict["images"] as? NSArray {
if let array2 = array[0]["scores"] as? NSArray {
if let ids = array2.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}
}
}
or all in one shot:
if let ids = (dict["images"]?[0]["scores"])?.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}
{
QueueId = 27;
SongId = 38;
artWorkURL = "<null>";
duration = 58258;
"stream_url" = "https://api.soundcloud.com/tracks/233301835/stream";
title = Magenta;
trackID = 233301835;
userAvatar = "https://i1.sndcdn.com/avatars-000188204071-llusgk-large.jpg";
userName = Agiv;
},
{
QueueId = 27;
SongId = 39;
artWorkURL = "<null>";
duration = 79000;
"stream_url" = "https://api.soundcloud.com/tracks/233301833/stream";
title = Nino;
trackID = 233301833;
userAvatar = "https://i1.sndcdn.com/avatars-000157591669-eva3mg-large.jpg";
userName = "SWR Umwelt und Ern\U00e4hrung";
}
My array of dictionary format is as above and multiple tracks i want to check 27 is already there or not ?
You can do this with the filter function
let queueID27Exists = !array.filter({$0["QueueId"] as? Int == 27}).isEmpty
This answer is for your previous JSON object!
if let results : NSDictionary = post.objectForKey("data") as? NSDictionary {
let array:NSArray = (results.valueForKey("track") as! NSArray)
if "25" == array[0].valueForKey("trackID") as? String {
NSLog("YES")
} else {
NSLog("NO")
}
}
var found = false
for (_, data) in post {
let track = data["track"]
if track["trackID"] == "25" {
found = true
}