Reputation: 839
I'm trying to iterate an array of a custom class I've made, but it's tell me not all code paths return a value. In Java, most certainly all paths return a value.
function PointLiesWithinAtleast1Polygon(point: CLLocationCoordinate2D, polygons: Array<GMSPath>){
polygons.forEach(polygon =>{
if(GMSGeometryContainsLocation(point, polygon)){
return true;
}
});
return false;
}
The polygons array is iterated and if the conditions are met then it returns true and the function is ended. If the condition isn't met then the loop breaks and returns false. Why is it saying not all code paths return a value?
Upvotes: 1
Views: 605
Reputation: 1093
The method PointLiesWithinAtleast1Polygon
always return false
. When you do return true;
in your lambda function, you're exiting the lambda and returning in the PointLiesWithinAtleast1Polygon
function.
Java version
function PointLiesWithinAtleast1Polygon(point: CLLocationCoordinate2D, polygons: Array<GMSPath>){
for (GMSPath polygon : polygons)
{
if(!GMSGeometryContainsLocation(point, polygon)){
return false;
}
}
return true;
}
Like you said in the comment, you can either define a boolean outside the anonymous function, or you can use normal for loop
and check if the criteria isn't met.
In Typescript, you can use the every
method of Array
to check that every object has a certain criteria.
function PointLiesWithinAtleast1Polygon(point: CLLocationCoordinate2D, polygons: Array<GMSPath>){
return polygons.every((polygon: GMSPath) =>{
return GMSGeometryContainsLocation(point, polygon);
});
}
Upvotes: 3