gpt4 book ai didi

ios - 访问特定索引中的数组

转载 作者:行者123 更新时间:2023-11-28 12:32:18 24 4
gpt4 key购买 nike

我正在尝试访问函数中的数组,据我所知,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: Cannot subscript a value of type '[ViewController.Point]' with an index of type 'ViewController.Point'

错误一:

/Users/user/Desktop/proj/ViewController.swift:149:38: Cannot subscript a value of type '[ViewController.Point]' with an index of type 'ViewController.Point'

代码有什么问题?谢谢!

最佳答案

您的 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
}
}

附言:也看看this question "Sort array by calculated distance in Swift"为了更好地计算距离。只需按距离对数组进行排序,然后在排序后从数组中取出第一个。那更容易做到

关于ios - 访问特定索引中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com