How can i get output like this in swift - swift

{ length = 30, contents = "something", count = 32.3 }
I need exact output in this bracket { } not in() or []
var array:Array<Any> = Array<Any>();
array.append(NSDictionary(object: singleItem.name, forKey: "name" as NSCopying));
array.append(NSDictionary(object: singleItem.planned_revenue, forKey: "planned_revenue" as NSCopying));
array.append(NSDictionary(object: singleItem.phone, forKey: "phone" as NSCopying));
array.append(NSDictionary(object: singleItem.description, forKey: "description" as NSCopying));
array.append(NSDictionary(object: singleItem.email_from, forKey: "email_from" as NSCopying));
array.append(NSDictionary(object: singleItem.probability, forKey: "probability" as NSCopying));
output
[{
name = "this is another";
}, {
"planned_revenue" = "0.0";
}, {
phone = "";
}, {
description = "Internal Notes";
}, {
"email_from" = "thomas.passot#agrolait.example.com";
}, {
probability = "20.0";
}]
I need like
[{ name = "this is another", "planned_revenue" = "0.0", phone = "", description = "Internal Notes", ..... }]

First, you need a dictionary, not an array of dictionaries. Using Swift, you can use Dictionary instead of NSDictionary (Dictionary<String, Any> or [String: Any]):
let dict: [String: Any] = [
"name": singleItem.name,
"planned_revenue": singleItem.planned_revenue,
"phone": singleItem.phone,
"description": singleItem.description,
"email_from": singleItem.email_from,
"probability": singleItem.probability
]
// If you need a NSDictionary, you can cast it
let nsDict = dict as NSDictionary
Take a look at Collection Types in the Swift guide and the Dictionary class reference for more information.

Related

Swift: convert [Dictionary<String, [String : Double]>.Element] to [String : [String : Double]]

I have this JSON string:
[
{
"name": "first_category",
"model": {
"OK": 0.49404761904761907,
"NOPE": 0.48214285714285715
}
},
{
"name": "second_category",
"model": {
"YOP": 0.389338593,
"GO": 0.20420894
}
}
]
I have created this struct to decode it:
struct JSONModel: Codable {
let name: String
let model: [String: Double]
}
The decoding:
let decodedModel = try? decoder.decode([JSONModel].self, from: Data(jsonString.utf8))
It correctly fills the array as expected, but now I would like to use this array to create a dictionary whose keys would be the JSONModel names, and values the models. This is what I expect to get:
[
"first_category": [
"OK": 0.49404761904761907,
"NOPE": 0.4821428571428571
],
"second_category": [
"YOP": 0.389338593,
"GO": 0.20420894
]
]
So I tried this:
let simplifiedModel: [String: [String: Double]] = decodedModel.flatMap { [$0.name: $0.model] }
But I'm getting this error:
Cannot convert value of type '[Dictionary<String, [String : Double]>.Element]' to closure result type '[String : [String : Double]]'
What should I do instead?
Thank you for your help
I would use reduce(into:) for this
let dictionary = decodedModel.reduce(into: [:]) {
$0[$1.name] = $1.model
}

Trying to make the search bar functionality filter the names of the contacts which are coming from a json object into an array of strings

Want to convert my json object into an array of just names so I can use the search bar to search for different names and filter it.
"data2": {
"id": 1,
"contacts": [
{
"name": "Molly",
"pictureUrl": "molly"
},
{
"name": "Cathy",
"pictureUrl": "molly"
},
{
"name": "Bob",
"pictureUrl": "bob"
},
{
"name": "Nick",
"pictureUrl": "clothes"
}
],
},
"error": 0,
"message": "Success"
This is the json file with the object:
var contact = [IndividualContact]()
init?(data2: Data) {
do {
if let json2 = try JSONSerialization.jsonObject(with: data2) as? [String: Any], let body = json2["data2"] as? [String: Any] {
if let contacts = body["contacts"] as? [[String: Any]] {
self.contact = ( contacts.map { IndividualContact(json2: $0) } )
//Expected: ["Molly", "Bob", "Cathy"]
}
}

How to retrive the whole object at once from Firebase?

I've just started using Firebase for my Swift programming . I managed to fetch some data from the Json using the following :
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").child("Like").observeSingleEvent(of: .value, with: { (Snapshot) in
let Value = Snapshot.value as? Int
print(Value!)
})
However , I am trying to fetch the whole object first and then get the value of each element later . So here is my attempt but my app keeps getting terminated :
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: FIRDataEventType.childAdded, with: { (snapshot) in
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
Any idea where am I making a mistake ?
here is my Json :
{
"Posts": {
"1": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
},
"2": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
}
},
"User": {
"1": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
},
"2": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
}
}
}
Try printing snapshot first and see if you are able to retrieve anything if no, Try this
Use FIRDataEventType as .value instead of .childAdded. Since .childAdded is only fired when a child node is added to that reference node, .value retrieves the current value as that reference point..
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
if you want to get the post object you need to access snapshot.value also observe for value event instead of childAdded.
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post")
.observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String:Any] {
print(dict["Like"] as? Int ?? 0)
}
})

how can I construct the alamofire query based on array entries in Swift?

I have a class SingleUser:
class SingleUser: NSObject, NSCoding {
var username: String
var display_name: String
var facebook_username: String
var device_id: String
.
.
.
}
and I have an array of those users:
let blockedUsers: [SingleUser] = NSKeyedUnarchiver.unarchiveObject(with:
(defaults.object(forKey: "myUsers") as! Data)) as! [SingleUser]
I want to pass it with Alamofire to my webservice.
I have already some parameters defined:
var params = [
"long": lon as AnyObject,
"lat": lat as AnyObject,
"startDate": DateCalc.convertValueToDate(defaults.float(forKey: "startDate")) as AnyObject,
"endDate": DateCalc.convertValueToDate(defaults.float(forKey: "endDate")) as AnyObject
] as [String: AnyObject]
and now I want to append my users somehow, e.g. as:
"users" = {
{ "username" = "xxxx",
"display_name" = "xxxx",
"facebook_username" = "xxxx",
"device_id" = "xxxx"
},
{ "username" = "yyyy",
"display_name" = "yyyy",
"facebook_username" = "yyyy",
"device_id" = "yyyy"
},
.
.
.
}
Can you tell me how could I iterate over that array and append it to my params array?
class SingleUser: NSObject, NSCoding {
var username: String
var display_name: String
var facebook_username: String
var device_id: String
var jsonFormat: [String: AnyObject] {
return ["username": username,
"display_name": display_name,
"facebook_username": facebook_username,
"device_id": device_id]
}
}
And then:
var users = [[String: AnyObject]]()
blockedUsers.forEach { user in
users.append(user.jsonFormat)
}
params["users"] = users

Swift - Cast from [SKNode] to unrelated type 'String' always fails

I am beginner in swift language and currently i am developing some App (Game).
But i have problem when casting AnyObject to String or else, which is always give warning "Cast from [SKNode] to unrelated type 'String' always fails"
Here my code
var facets = [AnyObject]()
init () {
facets = [
[
"id": "1",
"lang": ["id": "Memori", "en": "Memory"]
],
[
"id": "2",
"lang": ["id": "Kecepatan Berpikir", "en": "Speed"]
],
[
"id": "3",
"lang": ["id": "Fungsi Eksekutif", "en": "Control"]
],
[
"id": "4",
"lang": ["id": "Konsentrasi", "en": "Attention"]
],
[
"id": "5",
"lang": ["id": "Pemecahan Masalah", "en": "Problem Solving"]
]
]
}
func findFacetUsingId(id: String?) -> String? {
if let id = id {
for value in facets {
var facet_id: String = value["id"] as! String
if id == facet_id {
var names: Dictionary<String, String> = value["lang"] as! Dictionary<String, String>
return names[Lang.ID]
}
}
}
return nil
}
Here the screenshot,
By the way, I got success when using this code
var facet_id: String = value.objectForKey("id") as! String
instead of
var facet_id: String = value["id"] as! String
But the App to be slow (very very slow)
Thank you in advance
Actually your code works if you just do a little change:
func findFacetUsingId(id: String?) -> String? {
if let id = id {
for value in facets {
var facet_id: String = value["id"] as! String
if id == facet_id {
var names: Dictionary<String, String> = value["lang"] as! Dictionary<String, String>
return names["id"]
}
}
}
return nil
}