Condition for while loop not working, unable to populate tableview cells - ios6

I'm a beginner to ios and am building my first app...so go easy on me :-)
I am trying to display the results from a web service in tableview cells. However my while loop condition is failing. I moved the nslog into the while loop and it clearly prints the objects in the array as you would expect. However there is something wrong when it ends I believe.
Does anyone have any ideas as to why it is failing?
Basically I'm trying to get 'Recipe name' and 'smallImageUrls; from the web service results and print that in a tableview cell.
I know my tableview cell wont print properly as is. I'll address that in a bit. Probably extract the urls into one array and then use that array to in the tableviewcell method.
Any assistance anyone can provide is greatly appreciated. I just find it strange as it is clearly going through the while loop without any issues. :-S
No real error message just:
self SearchedYummlyViewController * 0x12b39570
matchesCount int 40
in the left part of the pane at the bottom.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.searchYummlyRecipeResults = [NSJSONSerialization JSONObjectWithData:self.yummlyRecipesNSData options:nil error:nil];
self.tempYummlyResultsMatches = [[NSMutableArray alloc]init];
int matchesCount = 0;
while([self.searchYummlyRecipeResults[#"matches"]objectAtIndex:matchesCount]){
[self.tempYummlyRecipeMatch addObject:[[self.searchYummlyRecipeResults[#"matches"]objectAtIndex:matchesCount]objectForKey:#"recipeName"]];
[self.tempYummlyRecipeMatch addObject:[[self.searchYummlyRecipeResults[#"matches"]objectAtIndex:matchesCount]objectForKey:#"smallImageUrls"]];
NSLog(#"tempYummlyRecipeMatch array's contents: %#", self.tempYummlyRecipeMatch);
matchesCount++;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
NSString *recipeString = self.tempYummlyRecipeMatch[indexPath.row];
cell.textLabel.text = recipeString;
//The below is code on how to add a image from a web service to a cell. I dont think that will work but my code cant make it down there yet so I'll tackle that after while loop issue.
NSURL *url = [NSURL URLWithString:self.tempYummlyRecipeMatch[indexPath.row+1];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
cell.imageView.image = image;
return cell;
}
Example of the webservice output below:
Recipe List: {
attribution = {
html = "<a href='http://www.yummly.com/recipes/onion-soup'>onion soup recipes</a> search powered by <img src='http://static.yummly.com/api-logo.png'/>";
logo = "http://static.yummly.com/api-logo.png";
text = "onion soup recipes: search powered by Yummly";
url = "http://www.yummly.com/recipes/onion-soup";
};
criteria = {
allowedIngredients = (
);
excludedIngredients = (
);
facetFields = (
);
maxResults = 6;
requirePictures = 0;
resultsToSkip = 0;
terms = (
onion,
soup
);
};
facetCounts = {
};
matches = (
{
attributes = {
};
flavors = {
bitter = "0.1666666666666667";
meaty = "0.3333333333333333";
piquant = 0;
salty = "0.5";
sour = "0.3333333333333333";
sweet = "0.5";
};
id = "French-onion-soup-sandwiches-309090";
ingredients = (
"olive oil",
"sea salt",
"fresh thyme leaves",
"granulated sugar",
"yellow onions",
"unsalted butter",
"beef broth",
"cracked black pepper",
"gruyere cheese",
bread
);
rating = 0;
recipeName = "French Onion Soup Sandwiches";
smallImageUrls = (
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
);
sourceDisplayName = "Joy the Baker";
totalTimeInSeconds = 0;
},
{
attributes = {
course = (
"Main Dishes"
);
};
flavors = {
bitter = 1;
meaty = "0.1666666666666667";
piquant = 0;
salty = 1;
sour = "0.1666666666666667";
sweet = "0.3333333333333333";
};
id = "Awesome-Slow-Cooker-Pot-Roast-Allrecipes";
ingredients = (
"condensed cream of mushroom soup",
"onion soup mix",
"pot roast",
water
);
rating = "4.69";
recipeName = "Awesome Slow Cooker Pot Roast";
smallImageUrls = (
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
);
sourceDisplayName = AllRecipes;
totalTimeInSeconds = 29400;
},
{
attributes = {
course = (
Soups,
Appetizers
);
cuisine = (
French
);
holiday = (
Thanksgiving
);
};
flavors = {
bitter = "0.1666666666666667";
meaty = "0.1666666666666667";
piquant = 0;
salty = "0.1666666666666667";
sour = "0.1666666666666667";
sweet = "0.1666666666666667";
};
id = "French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364";
ingredients = (
"stick butter",
"french bread",
"yellow onion",
"low sodium chicken broth",
"gruyere cheese",
"minced garlic",
"dry white wine",
"worcestershire sauce",
"beef broth"
);
rating = 0;
recipeName = "French Onion Soup";
smallImageUrls = (
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
);
sourceDisplayName = "The Pioneer Woman";
totalTimeInSeconds = 0;
},
{
attributes = {
course = (
Soups
);
};
flavors = "<null>";
id = "Curried-sweet-potato-soup-333086";
ingredients = (
broth,
salt,
"sweet potatoes",
"lite coconut milk",
onion,
"coconut oil",
"curry powder",
garlic,
spinach,
lime,
"chopped cilantro",
"red pepper flakes",
"brown sugar",
peas
);
rating = 0;
recipeName = "Curried Sweet Potato Soup";
smallImageUrls = (
"http://i.yummly.com/Curried-sweet-potato-soup-333086-295006.s.jpg"
);
sourceDisplayName = "Camille Styles";
totalTimeInSeconds = 0;
},
{
attributes = {
};
flavors = "<null>";
id = "French-onion-soup-grilled-cheese-308496";
ingredients = (
"unsalted butter",
"kosher salt",
"sweet onions",
"unsalted beef stock",
pepper,
"gruyere cheese",
"dry sherry",
"italian bread",
"fresh thyme"
);
rating = 0;
recipeName = "French Onion Soup Grilled Cheese";
smallImageUrls = (
"http://i.yummly.com/French-onion-soup-grilled-cheese-308496-272505.s.jpg"
);
sourceDisplayName = "The Kitchn";
totalTimeInSeconds = 0;
},
{
attributes = {
};
flavors = {
bitter = 1;
meaty = 1;
piquant = 0;
salty = 1;
sour = 1;
sweet = "0.8333333333333334";
};
id = "Vidalia-onion-soup-with-wild-rice-and-blue-cheese-305366";
ingredients = (
"vidalia onions",
"chicken stock",
herb,
pepper,
"wild rice",
"unsalted butter",
baguette,
salt,
"extra virgin olive oil",
other
);
rating = 0;
recipeName = "Vidalia Onion Soup with Wild Rice and Blue Cheese";
smallImageUrls = (
"http://i.yummly.com/Vidalia-onion-soup-with-wild-rice-and-blue-cheese-305366-268824.s.jpg"
);
sourceDisplayName = "Smitten Kitchen";
totalTimeInSeconds = 0;
},
Example of tempYummlyRecipeResults nslog
tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
)
)
2013-02-27 22:13:34.334 CustomTableView[435:11303] tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
),
"Awesome Slow Cooker Pot Roast",
(
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
)
)
2013-02-27 22:13:34.335 CustomTableView[435:11303] tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
),
"Awesome Slow Cooker Pot Roast",
(
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
),
"French Onion Soup",
(
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
)
)
2013-02-27 22:13:34.335 CustomTableView[435:11303] tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
),
"Awesome Slow Cooker Pot Roast",
(
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
),
"French Onion Soup",
(
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
),
"Curried Sweet Potato Soup",
(
"http://i.yummly.com/Curried-sweet-potato-soup-333086-295006.s.jpg"
)
)
2013-02-27 22:13:34.335 CustomTableView[435:11303] tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
),
"Awesome Slow Cooker Pot Roast",
(
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
),
"French Onion Soup",
(
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
),
"Curried Sweet Potato Soup",
(
"http://i.yummly.com/Curried-sweet-potato-soup-333086-295006.s.jpg"
),
"French Onion Soup Grilled Cheese",
(
"http://i.yummly.com/French-onion-soup-grilled-cheese-308496-272505.s.jpg"
)
)
2013-02-27 22:13:34.335 CustomTableView[435:11303] tempYummlyRecipeMatch array's contents: (
"French Onion Soup Sandwiches",
(
"http://i.yummly.com/French-onion-soup-sandwiches-309090-273265.s.jpg"
),
"Awesome Slow Cooker Pot Roast",
(
"http://i2.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-2.s.png",
"http://i.yummly.com/Awesome-Slow-Cooker-Pot-Roast-Allrecipes-58919.s.png"
),
"French Onion Soup",
(
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1512.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-1199.s.jpg",
"http://i.yummly.com/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364-220.s.jpg"
),
"Curried Sweet Potato Soup",
(
"http://i.yummly.com/Curried-sweet-potato-soup-333086-295006.s.jpg"
),
"French Onion Soup Grilled Cheese",
(
"http://i.yu

At the end of your connectionDidFinishLoading, you should reload your table view.
[self.tableView reloadData];
Just updating your array does not instantly update your table view.
EDIT: You are right, your while loop condition is incorrect. Currently, it only checks if the object at index matchesCount is not nil (somewhat similar to while(object) or while(object != nil)). I think what you are looking for is if the number of objects in the array is greater than matchesCount so as to prevent an array index out of bounds exception. To do so, you need to use while([self.searchYummlyRecipeResults[#"matches"] count] > matchesCount).

Related

Find index of Custom List - Kotlin

I have a list
val SongList = [SongInfo(name="Dark Star", rawId="2131689475", time=1:30), SongInfo(name="Can't let go", rawId="2131689474", time=1:24), , SongInfo(name="Big Digits", rawId="2131689473", time=0:49), SongInfo(name="What's Mine", rawId=2131689478]
and to get the song name I do this
val song = songList[0].name
shuffling song
songList.shuffle()
how do I find an index of song, after shuffling the list?
My code isn't the best solution but it finds the index, and return the song name by index.
data class SongInfo(var name: String, var rawId: String, var time: String)
fun main() {
val songList = listOf(
SongInfo(name = "Dark Star", rawId = "2131689475", time = "1:30"),
SongInfo(name = "Can't let go", rawId = "2131689474", time = "1:24"),
SongInfo(name = "Big Digits", rawId = "2131689473", time = "0:49"),
SongInfo(name = "What's Mine", rawId = "2131689478", time = "22:31")
)
val song = songList[0].name
val shuffledSongList = songList.shuffled()
println(shuffledSongList)
var index = 0
while (true) {
if (shuffledSongList[index].name == song) break
index++
}
println(shuffledSongList[index].name)
}

array of object retrieving data and average

I've just started learning JavaSCript and I have some trouble with this exercise.
I have an array of objects with around 250 object in it. There are multiple movies in it (I pasted only the first 2 movies in the array but the structure is the same):
Create a dramaMoviesRate() function that receives an array as a parameter to get the average rate of all drama movies! Let's see if it is better than the general average.
Again, rounded to 2 decimals!
My logic is: 1)select only the movies that include the string 'Drama', and 2)calculate the average of them.
My problem is: according to the test I should store everything into a function. And secondly, when I try to filter Drama movies I also get other movies that don't contain that string as output.
Please use JS ES5 syntax, thank you.
PS: I MUST USE ONLY THE METHODS I KNOW WHICH ARE:
filter() map() reduce() sort() reverse() slice()
let movies = [
{
title: "The Shawshank Redemption",
year: 1994,
director: "Frank Darabont",
duration: "2h 22min",
genre: ["Crime", "Drama"],
rate: 9.3,
},
{
title: "The Godfather",
year: 1972,
director: "Francis Ford Coppola",
duration: "2h 55min",
genre: ["Crime", "Drama"],
rate: 9.2,
}
]
function howManyDrama(phDrama) {
const drama = phDrama.filter(function (movie) {
return (
movie.genre.includes('Drama')
);
});
return drama;
} ==>//HERE I DON'T GET THE RIGHT OUTPUT
//console.log(movies)
function dramaMoviesRate(pdrama){
const average = pdrama.reduce(function(acc, movie){
return acc + movie.rate
},0);
return Math.round((average / pdrama.length) * 100) / 100;
}
-----------------------------------------------------------------
-----------------------------------------------------------------
//I also thought to filter my drama movies and then store the //function that has an array as output as argument of my second //function like this:
function howManyDrama(phDrama) { //thats the fist to filter //drama with incorrect output
const drama = phDrama.filter(function (movie) {
return (
movie.genre.includes('Drama')
);
});
return drama;
}
function dramaMoviesRate(howManyDrama){
const average = howManyDrama.reduce(function(acc,movie){
return acc.movie.rate
},0);
return Math.round((average / howManyDrama.length) * 100) / 100
}
howManyDrama(movies)
dramaMoviesRate(howManyDrama)
Please use ES5 Syntax. Thanks for the patience!
I ran you code. The Drama filter is working correctly. I updated the totaling process to be cleaner. I could not get the reduce method to work correctly, so I used map instead.
Try this code:
let movies = [
{
title: "The Shawshank Redemption",
year: 1994,
director: "Frank Darabont",
duration: "2h 22min",
genre: ["Crime", "Drama"],
rate: 9.3,
},
{
title: "The Godfather",
year: 1972,
director: "Francis Ford Coppola",
duration: "2h 55min",
genre: ["Crime", "Drama"],
rate: 9.2,
},
{
title: "Mission Impossible",
year: 1999,
director: "zzz",
duration: "2h 55min",
genre: ["Action"],
rate: 7.2,
}
]
function howManyDrama(phDrama) {
const drama = phDrama.filter(function (movie) {
return (
movie.genre.includes('Drama')
);
});
return drama;
}
function dramaMoviesRate(pdrama){
let total = 0
let result = pdrama.map(x => total += x.rate);
return total/pdrama.length
}
let m = howManyDrama(movies)
console.log(m) //correct
let r = dramaMoviesRate(m)
console.log(r) // correct
// do everything in single function
function dramaRate(movielist) {
const drama = movielist.filter(function (movie) {
return (
movie.genre.includes('Drama')
);
});
let total = 0
let result = drama.map(x => total += x.rate);
return total/drama.length
}
console.log(dramaRate(movies)) //single function call

How to push an array into json key/value pair of an object i codeigniter array

What am I trying to achieve
So what I was trying to achieve was push an array key/value pair into a JSON object that is in itself an array, so that there is a single object and one of the key-value pairs contains an array.
THIS IS WHAT I AM TRYING TO ACHIEVE as JSON output, another data2 Array inside another data array.
[
{
"data": {
"temp_service_id": "3",
"name": "health checkup",
"price": "10000",
"service_id": "41",
"data2": [
{
"fees": "2000",
"service_name": "Anaesthesiologist"
},
{
"fees": "300",
"service_name": "Andrologist"
},
]
},
}
]
What I have tried
THIS IS MY CONTROLLER :
$where['subtype_id'] = $this->post('org_id');
$where['is_active'] = 'Y';
$table_package_master = 'package_master';
$fetch_package_name = $this->$model_name->fetch($table_package_master,$where);
$array = [];
$array1 = [];
$array2 = [];
if($fetch_package_name){
foreach($fetch_package_name as $row){
$where_r['t1.package_num'] = $row->package_num;
$where_r['t1.is_active'] = 'Y';
$where_r['services.is_active'] = 'Y';
$where_r['t4.is_active'] = 'Y';
$fetch_packages1 = $this->$model_name->fetch_packages1($where_r);
$array['data'] = $fetch_packages1;
$fetch_packages = $this->$model_name->fetch_packages($where_r);
foreach($fetch_packages as $row1){
$where_re['services.service_id'] = $row1->service_id;
$where_re['services.is_active'] = 'Y';
$where_re['template_services.is_active'] = 'Y';
$fetch_package_ser = $this->$model_name->fetch_service_details($where_re);
array_push($array1,$fetch_package_ser);
}
}
$array['data2'] = $array1;
$array3 = [$array];
$this->response($array3);
}
THIS IS MY MODEL :
function fetch($table,$where_con){
$this->db->select('*')->from($table)->where($where_con);
return $this->db->get()->result();
}
function fetch_packages1($where){
$this->db->select('t3.temp_service_id,t4.name,t4.price,services.service_id');
$this->db->from('package_services as t1');
$this->db->join('services','services.service_id = t1.service_id', 'LEFT');
$this->db->join('template_services as t3','t3.temp_service_id = services.temp_service_id' , 'LEFT');
$this->db->join('package_master as t4', 't4.package_num = t1.package_num','LEFT');
$this->db->where($where);
$this->db->group_by('t1.package_num');
return $this->db->get()->row();
}
function fetch_service_details($where){
$this->db->select('services.price as fees,template_services.service_name');
$this->db->from('services');
$this->db->join('template_services','template_services.temp_service_id =
services.temp_service_id','LEFT');
$this->db->where($where);
return $this->db->get()->row();
}
Basically what I am trying to do is put a data object inside $array variable that is data coming from one table now what i did was push data from another query into $array1
Than at the end all i did was array_push into $array3 all the data from $array1 and $array2 to make them join together but
MY OUTPUT IS THIS :
[
{
"data": {
"temp_service_id": "3",
"name": "health checkup",
"price": "10000",
"service_id": "41"
},
"data2": [
{
"fees": "2000",
"service_name": "Anaesthesiologist"
},
{
"fees": "300",
"service_name": "Andrologist"
}
]
}
]
What am i missing here? i am really confused and can't understand how to push data2 array.
Thankyou in advance :)
Re-write one line in your Controller $array['data2'] = $array1; with $array->data['data2'] = $array1;.
It will put array data2 into the data index.
Working Demo
I came up with a solution finally after thinking about it a lot
$fetch_package_name = $this->$model_name->fetch($table_package_master,$where);
$array = [];
$array1 = [];
if($fetch_package_name){
for($i=0;$i<sizeof($fetch_package_name); $i++){
$where_r['t1.package_num'] = $fetch_package_name[$i]->package_num;
$where_r['t1.is_active'] = 'Y';
$where_r['services.is_active'] = 'Y';
$where_r['t4.is_active'] = 'Y';
$fetch_packages1 = $this->$model_name->fetch_packages1($where_r);
$array[$i]['name'] = $fetch_package_name[$i]->name;
$array[$i]['price'] = $fetch_package_name[$i]->price;
$where_re['t1.package_num'] = $fetch_package_name[$i]->package_num;
$where_re['t1.is_active'] = 'Y';
$where_re['services.is_active'] = 'Y';
$fetch_packages = $this->$model_name->fetch_packages2($where_re);
for($j=0; $j<sizeof($fetch_packages); $j++){
$array1[$j]['service_name'] = $fetch_packages[$j]->service_name;
$array1[$j]['price'] = $fetch_packages[$j]->price;
}
$array[$i]['data2'] = $array1;
}
// $this->response($array);
$array2['data'] = $array;
$array2['status'] = 10007;
// $data_response['data'] = $array;
$this->response($array2);
}
IT gave me the response that i desired in the first place.\
{
"data":[
{
"name":"Full body checkup",
"price":"5000",
"data2":[
{
"service_name":"Allergist",
"price":"23"
},
{
"service_name":"Andrologist",
"price":"300"
}
]
}
],
}
Cheers! happy coding :-)

How to populate an array with a data from a function?

Hello I have the following function:
func parceDosi()
{
struct City{
let name : String
// let location : CLLocation
}
var cities = [City]()
var person = "Person"
let path: String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let jsonData = NSData(contentsOfFile: path) as NSData!
let ReadableJSON = JSON ( data:jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil )
NumberRows = ReadableJSON ["People"].count
for (var i = 0 ; i <= NumberRows; i++ )
{
Person += "\(i)"
let NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
let NameShirina = ReadableJSON ["People"] [Person] ["C1"].string as String!
let NameDuljina = ReadableJSON ["People"] [Person] ["D1"].string as String!
let latitude = (NameShirina as NSString).doubleValue
let longitude = (NameDuljina as NSString).doubleValue
// let loc = CLLocation( latitude: latitude, longitude: longitude)
// let ci = City(name: NameImeNaObekt, location: loc)
let ci = City( name: NameImeNaObekt)
cities.append(ci)
which reads information from a json file. The information which is read I want to return it into a
var data = [??]
this variable data works fine if it is in the following way:
var data = [New York, Boston, California] ,
but in stead of writing New York, Boston, California , I want to return the function
func parceDosi(),
because all of the cities are parsed there from a json file and I do not have to write every single one.Do you have an idea how to do that, I am new and something in my syntaxis is wrong.
Here is the JSON File:
{
"People": {
"Person0": {
"A1": "Безплатен Сок",
"B1": "Царево 11",
"C1": "43.0757",
"D1": "23.6172",
"E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person1": {
"A1": "Безплатна Бира",
"B1": "Царево 22",
"C1": "44.0757",
"D1": "24.6172",
"E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person2": {
"A1": "Безплатен Десерт",
"B1": "Царево 33",
"C1": "45.0757",
"D1": "25.6172",
"E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person3": {
"A1": "Безплатно Кафе",
"B1": "Царево 55",
"C1": "41.0757",
"D1": "21.6172",
"E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person4": {
"A1": "Безплатна Кола",
"B1": "Царево 66",
"C1": "46.0757",
"D1": "26.6172",
"E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
}
}
}
Each Person in the JSON contains 5 key-value pairs so I extended the struct City, the property location will be created from latitude and longitude:
struct City {
let name : String
let city : String
let location : CLLocation
let imageURL : NSURL
}
Since you're using SwiftJSON the parsing is quite clearly arranged
var cities = [City]()
func parceDosi() {
guard let url = NSBundle.mainBundle().URLForResource("jsonFile", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else {
print("Error finding JSON File")
return
}
let readableJSON = JSON(data: jsonData) // the mutable option is not needed.
let people = readableJSON["People"].dictionaryValue
for (_, person) in people {
let personName = person["A1"].stringValue
let cityName = person["B1"].stringValue
let latitude = person["C1"].doubleValue
let longitude = person["D1"].doubleValue
let imageURL = person["E1"].stringValue
let city = City(name: personName, city: cityName, location: CLLocation(latitude: latitude, longitude: longitude), imageURL: NSURL(string:imageURL)!)
cities.append(city)
}
// This is an example to get the nearest city from a given location
let myLocation = CLLocation(latitude: 50.0, longitude: 8.0)
let nearestlocations = cities.sort { (city1, city2) -> Bool in
return city1.location.distanceFromLocation(myLocation) < city2.location.distanceFromLocation(myLocation)
}
print(nearestlocations.first!)
}
PS: As you are responsible for the JSON file in the bundle, I recommend to use an array for the people (rather than a dictionary) and give the "chessboard"-keys more descriptive names.

Start Index of table at 0 in Lua

I want to set the index of table-members, but still name them. Is that possible?
local table = {
["cat"] = {
["fish"] = { stuff = "bla1", stuff2 = "bla" },
["mouse"] = { stuff = "bla2", stuff2 = "bla" },
["bird"] = { stuff = "bla3", stuff2 = "bla" },
},
["dog"] = {
["fish"] = { stuff = "bla1", stuff2 = "bla" },
["mouse"] = { stuff = "bla2", stuff2 = "bla" },
["bird"] = { stuff = "bla3", stuff2 = "bla" },
},
}
table["cat"][1] is fish, but I want that table["cat"][0] is fish, how can I achieve that?
Edit:
I still want to be able to access fish with table["cat"]["fish"].
Edit2:
What when I try to do it viceversa? http://repl.it/MCu
What am I doing wrong?
Just to clarify table["cat"][1] is not a fish -- your table example above does not make use of the index part of the table at all. To use the index part of the table, the key itself has to be an integer.
Modifying your example above:
local animal = {
cat = {
fish = { stuff = "bla", stuff2 = "bla" },
mouse = { stuff = "bla", stuff2 = "bla" },
bird = { stuff = "bla", stuff2 = "bla" },
},
dog = {
fish = { stuff = "bla", stuff2 = "bla" },
mouse = { stuff = "bla", stuff2 = "bla" },
bird = { stuff = "bla", stuff2 = "bla" },
},
}
If you want animal.cat.fish and animal.cat[1] to have the same value (the same lua table) just do a regular assignment:
animal.cat[1] = animal.cat.fish
-- and likewise if you want index 0:
animal.cat[0] = animal.cat.fish
Note that many of the standard lua functions that work with tables start counting from 1.
Your tables and the tables nested inside tables are pure hash-style, none array-style.
The array-style Lua tables:
local t = {"cat", "dog", "fish"}
is just a syntactic sugar of the equivalent form:
local t = {[1] = "cat", [2] = "dog", [3] = "fish"}
You can use all types of keys except nil, sure you can use integer keys starting from 0:
local t = {[0] = "cat", [1] = "dog", [2] = "fish"}
Note that starting from 0 made t no longer a sequence, so you lost the power of the table functions that is used only on sequences, like the #operator, ipairs, etc.
To build a table with different keys, you can make the value table first, and then bind different keys to the same table like this:
local v = {
["fish"] = { stuff = "bla", stuff2 = "bla" },
["mouse"] = { stuff = "bla", stuff2 = "bla" },
["bird"] = { stuff = "bla", stuff2 = "bla" },
}
local t = {
["cat"] = v,
[0] = v,
}
print(t.cat.fish.stuff, t[0].fish.stuff)
-- Output: bla bla
In this way, t.cat and t[0] access the same table.
Note that you can use the syntax sugar form table.cat.fish instead of table["cat"]["fish"]

Resources