我正在尝试访问函数中的数组,据我所知,Swift中没有Arraylists,所以我试图使用常规列表:
func findNearsetPoints(pointsArray: [Point] , myPoint: Point )-> Array <Point>{
var twoPoint = [Point]()
var minDist1:Double = DBL_MAX;
var minDist2:Double = DBL_MAX;
var distance:Double = 0
for element in pointsArray{
distance = getDistanceBetweenTwoPoints(pointsArray[element], Point); //error 0
if (distance < minDist1) {
minDist1 = distance;
twoPoint[1] = twoPoint[0];
twoPoint[0] = pointsArray[element]; // error 1
}
else if (distance < minDist2) {
minDist2 = distance;
twoPoint[1] = pointsArray[element]; //error 1
}
}
return twoPoint;
}
func getDistanceBetweenTwoPoints(point1:Point , point2:Point )->Double{
return 5; //TODO
}
错误0:
/Users/user/Desktop/proj/ViewController.swift:145:38:无法使用“ViewController.Point”类型的索引下标“[ViewController.Point]”类型的值
错误1:
/Users/user/Desktop/proj/ViewController.swift:149:38:无法使用“ViewController.Point”类型的索引下标“[ViewController.Point]”类型的值
代码有什么问题? 谢谢!
答案 0 :(得分:1)
您的element
已经是Point
而不是索引。
for element in pointsArray{
distance = getDistanceBetweenTwoPoints(point1: element, point2: myPoint) // fix here
if (distance < minDist1) {
minDist1 = distance;
twoPoint[1] = twoPoint[0];
twoPoint[0] = element; // fix here
}
else if (distance < minDist2) {
minDist2 = distance;
twoPoint[1] = element; // fix here
}
}
PS: 为了更好地计算距离,我也可以pagingEnabled 。只需按距离对数组进行排序,然后在排序后从数组中取出第一个数组。这更容易做到
答案 1 :(得分:1)
您声明getDistanceBetweenTwoPoints
为命名参数。
使用当前声明,您需要使用以下语法调用它:
getDistanceBetweenTwoPoints(point1: aPoint, point2: anotherPoint)
如果你想在参数上没有标签的情况下调用它,那么你应该重新定义它:
func getDistanceBetweenTwoPoints(
_ point1:Point ,
_ point2:Point )->Double{
return 5; //TODO
}