ios swfit - assign list of AnyObject to dictionary key - arrays

so i want to assign a list of AnyObject to a key of a dictionary with the structure [String:AnyObject]
here is my code:
let list = try JSONSerialization.jsonObject(with: newData, options: .allowFragments) as! [AnyObject]
let parsedResult = [String:AnyObject]()
parsedResult["dataList"] = list
callback(false, parsedResult)
im parsing data from an http request. i get this error:
Cannot assign value of type [AnyObject] to type AnyObject?
isn't a list of AnyObject, still an object?

Change:
let parsedResult = [String:AnyObject]()
To:
var parsedResult: [String: Any] = [ : ]
And by the way declare parsedResult as var to be able to do parsedResult["dataList"] = list.
For your other issue that you placed a comment on, do this instead:
if let account = data?["account"] as? [String: Any], let accountKey = account["key"] as? Int { ... }

Related

How Can I Put a Dictionary Inside An Array That's Nested In Another Dictionary? (Swift)

I want to add an array of dictionaries to an existing dictionary.
var details: [String : [String : String]] = [:]
viewDidLoad()
...
for i in 0..<count {
let hour = makeHourString()
details[hour] = [String: String] () as [String : String]
let dict = ["detailKey": "2100xx", "detailImage":"base64xx"]
details[hour].append(dict)
}
...
It is telling me: Value of type '[String : String]' has no member 'append.' But shouldn't it since it's an array?
I can get this kind of nested dictionary if I change the code to:
var details: [String: [Any]] = [:]
viewDidLoad()
...
for i in 0..<count {
let hour = makeHourString()
details[hour] = [String] () as [String]
let dict = ["detailKey": "2100xx", "detailImage":"base64xx"]
details[hour].append(dict)
}
...
Unfortunately, this isn't working for me because I need to able to store my data source using Codable. Any help is greatly appreciated.
This [String : String] is a Dictionary not an Array , According to your case you need
var details: [String: [[String:String]]] = [:]
and off course you can do this also
var details: [String:[Item]] = [:]
With
struct Item {
let detailKey, detailImage:String
}

Swift Array sort with JSON

Data:
tried get data from JSON
has code with Swift run on Playground
var roadWayStatusArray = [AnyObject]()
let url = URL(string: "http://od.moi.gov.tw/data/api/pbs")
let data = try? Data(contentsOf: url!)
let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if let results = json as? [String : AnyObject] {
if let result = results["result"] as? [[String : AnyObject]] {
for data in result {
let happendate = data["happendate"] as? String
roadWayStatusArray.append(data as AnyObject!)
}
}
}
I has tried using roadWayStatusArray.sort(by: >) but Xcode report me Ambiguous reference member '>'
How to create sort by hapendate or happentime
Your roadWayStatusArray is an array of AnyObject. There is no > operator defined for AnyObject.
The objects in roadWayStatusArray are actually dictionaries that look like this:
{
UID = "10602090007-0";
areaNm = "\U4e2d\U5c71\U9ad8\U901f\U516c\U8def-\U570b\U9053\Uff11\U865f";
comment = "\U5317\U4e0a.\U4e2d\U58e2\U670d\U52d9\U5340 \U51fa\U53e3\U531d\U9053\U4e2d \U53f3\U5074 \U5c0f\U5ba2\U8eca\U505c\U653e\Uff0c\U99d5\U99db\U7591\U4f3c\U7761\U8457\U4e86";
direction = "\U5317\U4e0a";
happendate = "2017-02-09";
happentime = "01:08:00.0000000";
modDttm = "2017-02-09 01:15:43.603";
region = N;
road = "";
roadtype = "\U5176\U4ed6";
srcdetail = "\U71b1\U5fc3\U807d\U773e";
x1 = "121.73558";
y1 = "25.12263";
}
You need to call sort(by:) with a closure that determines the sort order. For example, if you want to sort by happendate and then happentime:
roadWayStatusArray.sort(by: { (lhsAny, rhsAny) -> Bool in
let lhs = lhsAny as? [String: AnyObject]
let rhs = lhsAny as? [String: AnyObject]
let lhsKey = (lhs?["happendate"] as? String ?? "", lhs?["happentime"] as? String ?? "")
let rhsKey = (rhs?["happendate"] as? String ?? "", rhs?["happentime"] as? String ?? "")
return lhsKey < rhsKey
})

Why do I get the error "Ambiguous reference to member 'subscript'"?

The following code produces the compiler error:
Ambiguous reference to member 'subscript'
if let library = json as? [String: Any] {
if let books = library["books"] as? Array { // On this line
}
}
You need specify the type of your Array object.
if let books = dic["books"] as? Array<Dictionary<String, Any>> { //Or as? Array<Any>
//Or
if let books = dic["books"] as? [[String: Any]] { //Or as? [Any]

How to access nested JSON in brackets in Swift?

I have a JSON response which is in brackets and I struggle to access the inner fields e.g. display_name with Swift. How can I do that?
Optional(["result": {
user = {
"display_name" = "Max Test";
email = "test.max#gmail.com";
"fb_id" = 10209982554704497;
roles = (
stu
);
schools = "<null>";
};
}])
The code I used to access the JSON:
self.restApi.getProfileDetails() {responseObject, error in
//parse down the first layer of array
let response = responseObject as? [String:AnyObject]
print("response object when MyDetailsController opened")
print(response)
let result = response!["result"] as? [AnyObject]
print("result object")
print(result)
//parse down the second layer of JSON object
if let result = response!["result"] as? [AnyObject] {
print("result object when MyDetailsController opened")
// work with the content of "result", for example:
if let user = result[0] as? [String:AnyObject]{
print(user)
let displayName = user["display_name"]
print("displayName")
print(displayName)
}
}
It seems that I address the result in the wrong way as it is always nil:
The console output:
result object
nil
In response result is dictionary not array, try to get like this
let result = response!["result"] as? [String:AnyObject]
1-Get the result object from response
2-Get the user object from result object
3-Get the user info as String from user object .
let response = responseObject as? [String: AnyObject]
let result = response!["result"] as? [String: AnyObject]
if let user = result!["user"] as? [String: AnyObject] {
let displayName = user["display_name"] as? String
let email = user["email"] as? String
}

How we can find an element from [AnyObject] type array in swift

I have [AnyObject] array
var updatedPos = [AnyObject]()
I am setting data in that according to my requirement like!
let para:NSMutableDictionary = NSMutableDictionary()
para.setValue(posId, forKey: "id")
para.setValue(posName, forKey: "job")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
self.updatedPos.append(jsonString)
Now in my code i have some requirement to remove the object from this array where id getting matched according to requirement Here is the code which i am trying to implement
for var i = 0; i < updatedPos.count; i++
{
let posItem = updatedPos[i]
print("Id=\(posItem)")
let pId = posItem["id"] as? String
print("secRId=\(pId)")
if removeId! == pId!
{
updatedPos.removeAtIndex(i)
}
}
Here print("Id=\(posItem)") give me output asId={"id":"51","job":"Programmer"} but here i am not able to access id from this object. here print("secRId=\(pId)") give me nil
First of all use native Swift collection types.
Second of all use types as specific as possible.
For example your [AnyObject] array can be also declared as an array of dictionaries [[String:AnyObject]]
var updatedPos = [[String:AnyObject]]()
Now create the dictionaries and add them to the array (in your example the dictionary is actually [String:String] but I keep the AnyObject values).
let para1 : [String:AnyObject] = ["id" : "51", "job" : "Programmer"]
let para2 : [String:AnyObject] = ["id" : "12", "job" : "Designer"]
updatedPos.append(para1)
updatedPos.append(para2)
If you want to remove an item by id use the filter function
let removeId = "12"
updatedPos = updatedPos.filter { $0["id"] as? String != removeId }
or alternatively
if let indexToDelete = updatedPos.indexOf{ $0["id"] as? String == removeId} {
updatedPos.removeAtIndex(indexToDelete)
}
The JSON serialization is not needed for the code you provided.
PS: Never write valueForKey: and setValue:forKey: unless you know exactly what it's doing.
After some little bit stuffs I have found the very easy and best solution for my question. And I want to do special thanks to #vadian. Because he teach me new thing here. Hey Thank you very much #vadian
Finally the answer is I had covert posItem in json Format for finding the id from Id={"id":"51","job":"Programmer"} this string
And the way is
let data = posItem.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if let dict = json as? [String: AnyObject] {
let id = dict["id"]
if removeId! == id! as! String
{
updatedLoc.removeAtIndex(i)
}
}
}
catch {
print(error)
}

Resources