I have response from server I want to filter it and store in array using swift. Please help how to do it.
self.countryArrayvalue = (json?["list"] as! [Dictionary<String, Any>] as! NSArray) as! [Dictionary<String, Any>]
now i want to get country name from this self.countryArrayvalue and store in array.
Response is:
{
"error": false,
"error_code": 200,
"list": [
{
"country_id": "1",
"country_name": "Afghanistan",
"iso_code": "AF"
},
{
"country_id": "2",
"country_name": "Aland Islands",
"iso_code": "AX"
},
{
"country_id": "3",
"country_name": "Albania",
"iso_code": "AL"
} ]
}
You are making too many casting instead of single one.
self.countryArrayvalue = json?["list"] as! [[String: Any]]
Now to get array of country name try like this way.
self.countryNamesArray = self.countryArrayvalue.flatMap { $0["country_name"] as? String }
Related
I have a dictionary of type [String: Any] and I cannot get the total number of elements of internal dictionary.
struct ICP {
let staff = [
"teachers": [
[
"name": "Teacher One"
],
[
"name": "Teacher Two"
],
[
"name": "Teacher Three"
],
[
"name": "Teacher Four"
]
]
] as [String : Any]
}
I need to get the total number of teachers from the above dictionary.
First of all inside ICP struct you declared a constant variable named staff which contains a dictionary of kind [String: [[String: String]]] or shortly [String: [Any]], when you access teachers then you have a collection of single dictionaries which is kind of [[String: String]].
I suggest you to create a method inside the ICP class and call it teachersCount
Swift 5.1
Like:
struct ICP {
func teachersCount() -> Int {
guard let teachers = staff["teachers"] as? [[String: String]] else {return 0}
return teachers.count
}
You can call it outside of struct like:
ICP().teachersCount()
And Inside your struct like:
self.teachersCount()
struct Country {
var translations : [String:String?]? // must be defined as optionals!
}
// example entry
translationsDict = [
"translations": [
"de":"Deutschland",
"en": "germany",
"it": nil
]
]
How can I extract the values "Deutschland" and "germany" into a new array?
result should be:
["germany", "Deutschland"]
Firstly, get a collection of all values of translations, then convert it to an array.
if let collection = translationsDict["translations"]?.values {
let array = Array(collection)
print(array)
}
or
if let array = translationsDict["translations"]?.map({ $0.1 }) {
print(array)
}
Usually I just step into the dictionary and find the value once inside. In this case, I need to step in, loop through to find a value then step back out again then find a different value. Example:
address_components": [
{
"long_name": "E3 2AA",
"short_name": "E3 2AA",
"types": [
"postal_code"
]
},
{
"long_name": "London",
"short_name": "London",
"types": [
"postal_town"
]
}
]
This is what googles api dictionary looks like and I need to fetch the long_name of the postal_town.
You can use the first(where: function passing a closure to filter for the type, this avoids a loop:
if let addressComponents = json["address_components"] as? [[String:Any]],
let postalTownComponent = addressComponents.first(where: { ($0["types"] as! [String]).contains("postal_town") }) {
print(postalTownComponent["long_name"])
}
This should do it for you:
let result = addressComponents.filter({ return ($0["types"] as! [String]).contains("postal_town") }).map({ $0["long_name"] })
address_components is an array so you can just loop over it and check the value of your key. Maybe something like:
var names = []
for entry in addressComponent {
if addressComponent["types"][0] == "postal_town" {
names.append(addressComponent["long_name"])
}
}
Should it just that simple, or I misunderstand your question? An example:
let dict = [ "long_name": "E3 2AA", "short_name": "E3 2AA"]
for (key, value) in dict {
print("your key: \(key) and value: \(value)")
}
I was wondering how I could print just the names only or various if possible. At this point I have a simple for in Loop printing the entire collection.
var players: [[String: Any]] = [
["Name": "Joe Smith",
"Height": 42,
"Experience": true,
"Guardians": "Jime and Jan Smith",
"Team": ""],
["Name": "Jill Tanner",
"Height": 36,
"Experience": true,
"Guardians": "Clara Tanner",
"Team": ""],
["Name": "Bill Bon",
"Height": 43,
"Experience": true,
"Guardians": "Sara and Jenny Bon",
"Team": ""],
]
for teamSelector in players {
print(players)
}
Swift 3
For print the values:
players.values.forEach { (value) in
print(value)
}
For print the "name" (that called 'keys'):
players.keys.forEach { (key) in
print(key)
}
In other style you can write it like:
for key in players.keys{
print("The key is: \(key)")
print("The value is: \(players[key])")
}
You can do the following using your example, but updated to get the name:
for teamSelector in players {
print(teamSelector["Name"])
}
You can also use map to print all the names:
print(players.map { $0["Name"] })
Another option is to loop over each of the players and cast the name as a string and then display the name. Using flatMap here ensures all names are strings.
for name in players.flatMap({ $0["Name"] as? String }) {
print(name)
}
this would print only the names:
players.foreach() { print($0["Name"])
Here below is once again my hypothetical Users collection where more than one address is allowed:
{
"firstName": "Joe",
"lastName": "Grey",
...
"addresses":
[
{
"name": "Default",
"street": "...",
...,
"isDefault": true
},
{
"name": "Home",
"street": "...",
...,
"isDefault": false
},
{
"name": "Office",
"street": "...",
...,
"isDefault": false
}
]
}
Let's suppose I want to update the second address (Home) with the following new item:
{
"name": "New home",
"street": "Ruta del Sol"
},
How do I update the second item of the array with the new item, also considering that the new item might or might not provide all the fields of an address?
In this post Will shown me how to update a field at a given index, ensuring the address name remains unique. Now, instead of updating a single field, I want to update an entire item.
All you need to do is transform new json data for update . Example:
Let us assume you have new Json data with only two fields 'name' and 'isDefault' .
var newData = {"name" : "New Val","isDefault":true};
var updateData = {};
for (key in newData ) {
updateData["addresses.$."+key]=newData[key];
};
db.projectPlan.update({_id:1, 'addresses.name': 'Home'}, {$set:updateData});
var renamed = 'Office'; // from user input
var users = getUserMongoCollection();
var address = {
name: "Office,
street: "Ruta del Sol"
};
users.update({_id:userId },
{ $set : { 'addresses.1' : address } }, function(err){
//all done!
});