Here I need to get the index of particular array in which the key value pair item.defaultShipping == "true" then I need to the get the index of particular array and to pass in model class so that in order to get corresponding data so that it should be passed in another Api but when I tried below method it showing an error that Contexual type 'Any' cannot be used within dictionary literal in let parameters below line can anyone help me how to resolve this issue ?
here is my code
var i = 0
for item in customerShippingAddressModel {
if item.defaultShipping == "true" {
}
i += 1
}
let arr = customerShippingAddressModel[i]
let parameters : [String: Any] = ["address":
[ "region": "\(arr.region.region)",
"region_code": "\(arr.region.regionCode)",
"region_id": "\(arr.region.regionId)",
"country_id": "\(arr.countryId)",
"company": "\(arr.company)",
"telephone": "\(arr.telephone)",
"postcode": "\(arr.postCode)",
"city": "\(arr.city)",
"firstname": "\(arr.firstName)",
"lastname": "\(arr.lastName)",
"email": "\(arr.email)",
"prefix": "",
"sameAsBilling": 1,
"street": ["0": "\((arr.customerStreet[0])!)",
"1": "\((arr.customerStreet[1])!)"]]]
print(parameters)
Since Swift 3 you can use enumerated() which will allow you to have the index and the value as the following:
for (index, item) in customerShippingAddressModel.enumerated() {
if item.defaultShipping == "true" {
// you can get the item and index value here.
}
}
I am new to iOS development can any one give me some idea in swift. I have JSON data after parsing i am storing data in array like example.
"orderId" : 146,
"total" : 2,
"created_at" : "2016-09-19 11:08:51",
"categories" : [
{
"name" : "Bleach",
"qrCode" : "SRY-001-0098",
"weight" : 1,
"categoryId" : "57dbd9ca8e1a0919c9075d13",
"amount" : 1
},
{
"name" : "Normal (26+ lbs)",
"qrCode" : "SRY-001-0099",
"weight" : 1,
"categoryId" : "57dbd9708e1a094ecb10cfb1",
"amount" : 1
}
],
"completed_at" : "2016-09-19 00:00:00"
I have four arrays :
orderarray
totalarray
createatarrays
cartegoriesarray
completedarray
orderarray[0] = 146
totalarray[0] = 2
createatarrays[0] = "2016-09-19 11:08:51"
cartegoriesarray[0] =
[
{
"name" : "Bleach",
"qrCode" : "SRY-001-0098",
"weight" : 1,
"categoryId" : "57dbd9ca8e1a0919c9075d13",
"amount" : 1
},
{
"name" : "Normal",
"qrCode" : "SRY-001-0099",
"weight" : 1,
"categoryId" : "57dbd9708e1a094ecb10cfb1",
"amount" : 1
}
]
completedarray[0] = "2016-09-19 00:00:00"
Using indexpathrow i can able to display orderarray, totalarray, createdarray based on index path in tableview cell.
But here categoryarray how can i display inside array again two dictionary is there ?
I want to display name" : "Bleach", "name" : "Normal" in single tableview cell based on index path like categoryarray[0]
How to get these two names in single string plz give me some idea..
Thanks.
You need to loop the catergoryarray and get each dictionary out. Then you can get the individual values out of the dictionary.
var name = "";
//Loop the array of dictionaries
for dict in categoryarray as! NSDictionary {
//extract the items from the dictionary. and concatenate names
name = name + " " + dict["name"];
}
print("Name: ", name)
You can then use that information to populate your table cells as you wish. Obviously you will want to modify how the names are concatenated to suit your needs.
Hope that helps.
Let's imagine I have a Firebase setup like this, except with 10,000 users:
"users" : {
"user 1" : {
"latitude": 1234567,
"Longitude": 7654321,
"name": "Name 1"
},
"user 2" : {
"latitude": 1234567,
"longitude": 7654321,
"name": "Name 2"
},
"user 3" : {
"latitude": 1234567,
"Longitude": 7654321,
"name": "Name 3"
},
"user 4" : {
"latitude": 1234567,
"Longitude": 7654321,
"name": "Name 4"
},
}
What would be the least data-intensive way to generate a list of the 5 users closest to me? Very new to this, so the only solutions I can think of would require querying all 10,000 users.
I am very new to this subject, therefore I can only point you in the right direction. Essentially the way you're storing user location is not optimal. The best way to do it is to use GeoFire a newish addition to the Firebase service. How it works is you should have a large location object and you store the geolocation of those users using that users key. Here's an example.
{
Locations: {
-KH35xPkJmX0UTSG8DuM : {
"g" : "randomID",
"l" : {
"0" : "latitude",
"1" : "longitude"
}
}
}
}
{
Users: {
-KH35xPkJmX0UTSG8DuM : {
"username" : "Joe Sloan"
}
}
}
Your locations object will have 10,000 users keys and geoLocations. the value of "g" and "l" object are set when you use
geoFire.setLocation(CLLocation(latitude: 37.7853889, longitude: -122.4056973), forKey: "firebase-hq")
Google has optimized the query for users within a similar location.
let center = CLLocation(latitude: 37.7832889, longitude: -122.4056973)
// Query locations at [37.7832889, -122.4056973] with a radius of 600 meters
var circleQuery = geoFire.queryAtLocation(center, withRadius: 0.6)
The circleQuery variable should contain a Firebase dictionary of the closest users. As I said I haven't had a chance to really delve deeper but this should give you a start.
I have 3 lists:
a = ["John", "Archie", "Levi"]
b = ["13", "20"]
c = ["m", "m", "m", "m"]
I want to merge this into one list with dictionaries:
result = [
{"name": "John", "age": "13", "gender": "m"},
{"name": "Archie", "age": "20", "gender": "m"},
{"name": "Levi", "age": "", "gender": "m"},
{"name": "", "age": "", "gender": "m"},
]
Ok, this is pretty normal computer science problem. Here is an outline of how to go about solving it:
First, identify the inputs and the desired outputs. You've done that.
Note any edge cases you need to handle
Next, map out the logic flow using pseudo-code.
Convert from pseudo-code to real code.
Test and debug.
For step 2, your data suggests that you want to handle cases where you have different numbers of elements in each source array. it looks like you want to create a dictionary for all the 0 elements in each array, then a dictionary for the 1 elements, etc. When you run out of elements for a given array, it looks like you want to skip that key in your resulting dictionary entry.
Now to pseudo-code:
Find the array with the maximum number of elements. Make this your output_count (the number of items in your output array.)
Create an output array large enough for output_count entries.
Loop from 0 to output_count - 1.
create a dictionary variable
for each input array, if there are enough elements, add a key/value pair
for that array's key and the value at the current index. Otherwise skip
that key.
add the new dictionary to the end of your output array.
That should be enough to get you started. Now see if you can convert that pseudo-code to actual code, test it, and debug it. Report back here with your actual code, and feel free to ask for help if you get stuck getting your code working.
Try like this:
let a = ["John", "Archie", "Levi"]
let b = ["13", "20"]
let c = ["m", "m", "m", "m"]
var dicArray:[[String:String]] = []
for index in 0..<max(a.count,b.count,c.count) {
dicArray.append([:])
dicArray[index]["name"] = index < a.count ? a[index] : ""
dicArray[index]["age"] = index < b.count ? b[index] : ""
dicArray[index]["gender"] = index < c.count ? c[index] : ""
}
dicArray // [["gender": "m", "age": "13", "name": "John"], ["gender": "m", "age": "20", "name": "Archie"], ["gender": "m", "age": "", "name": "Levi"], ["gender": "m", "age": "", "name": ""]]
Here is my take. I first create the array, and then use enumerate() and forEach to process each array and add them to the array of dictionaries:
let a = ["John", "Archie", "Levi"]
let b = ["13", "20"]
let c = ["m", "m", "m", "m"]
let count = max(a.count, b.count, c.count)
var result = Array(count: count, repeatedValue: ["name":"", "age":"", "gender":""])
a.enumerate().forEach { idx, val in result[idx]["name"] = val }
b.enumerate().forEach { idx, val in result[idx]["age"] = val }
c.enumerate().forEach { idx, val in result[idx]["gender"] = val }
print(result)
[["gender": "m", "age": "13", "name": "John"], ["gender": "m", "age":
"20", "name": "Archie"], ["gender": "m", "age": "", "name": "Levi"],
["gender": "m", "age": "", "name": ""]]
This should do the job
let maxLength = max(a.count, b.count, c.count)
let paddedA = a + [String](count: maxLength-a.count, repeatedValue: "")
let paddedB = b + [String](count: maxLength-b.count, repeatedValue: "")
let paddedC = c + [String](count: maxLength-c.count, repeatedValue: "")
let res = zip(paddedA, zip(paddedB, paddedC)).map {
["name": $0.0, "age": $0.1.0, "gender": $0.1.1]
}
Output
[["gender": "m", "age": "13", "name": "John"], ["gender": "m", "age": "20", "name": "Archie"], ["gender": "m", "age": "", "name": "Levi"], ["gender": "m", "age": "", "name": ""]]
I'm learning Core Data and I need to create an Entity called Country. I'm getting this response from my API and I'm not sure how to create and store the JSON response in my country entity.
{
"total_count":10,
"results": [
{
"name": "Spain",
"population" : 45.000,
"location" : {
"latitude" : 29.567423,
"longitude" : -5.675326
}
},
{
"name": "France",
"population" : 25.000,
"location" : {
"latitude" : 29.567423,
"longitude" : -5.675326
}
},
{
"name": "Germany",
"population" : 15.000,
"location" : {
"latitude" : 29.567423,
"longitude" : -5.675326
}
}
]
}
The parent fields (name, population) are not problem, but how can I set the child fields (location key) in the entity graph? With an NSDictionary maybe?
There are many possibilities.
You can create two separate attributes like (latitude, longitude) having type (double, double) and at fetch time create location with both values or you can create CGPoint with both of values and then create string from CGPoint and store them
CGPoint location = CGPointMake(latitude, longitude);
NSString *stringLocation = NSStringFromCGPoint(point);
store that string and fetch it and then again convert into CGpoint and use it
CGPoint myPoint = CGPointFromString(stringLocation);