Swift偶然无限ForEach循环

我试图使用foreach循环,借助列表中递增的索引,在[[字符串]]中显示多个元素。但是,当我想生成列表时,不管指定的loop-count,循环都会无限重复。

这是我在循环中调用的函数,用于返回所需的字符串数组:

    func getPlaces (PlaceNumber: Int) -> [String]{
        
       
        if allPlaces.count - 1 >= PlaceNumber{
            
        return allPlaces[PlaceNumber]
        } else{
            
            return ["Not found",
                    "Not found",
                    "https://www.wikipedia.com",
                    "Not found",
                    "Not found"]
        }
    }

变量“allPlaces”是一个[[String]],其中有25个String-Arrays(0-24):

 let allPlaces: [[String]] =
    
    [["no sight",
      "No information",
      "https://www.wikipedia.com",
      "No information",
      "No information"],
     
     ["Tower of London",
      "The Tower of London, officially Her Majesty's Royal Palace and Fortress of the Tower of London, is a historic castle on the north bank of the River Thames in central London. It lies within the London Borough of Tower Hamlets, which is separated from the eastern edge of the square mile of the City of London by the open space known as Tower Hill. It was founded towards the end of 1066 as part of the Norman Conquest. The White Tower, which gives the entire castle its name, was built by William the Conqueror in 1078 and was a resented symbol of oppression, inflicted upon London by the new ruling elite. The castle was also used as a prison from 1100 until 1952, although that was not its primary purpose. A grand palace early in its history, it served as a royal residence.",
      "https://en.wikipedia.org/wiki/London_Bridge",
      "1066",
      "4"],

usw...

这是我的视图和要递增的函数(我使用索引访问[[字符串]]中的不同元素)。我认为循环应该像'places.allPlaces'-数组计数一样频繁地触发。但它会无限触发。即使我使用'0...24而不是“places.allPlaces”。

struct ListOfPlacesView: View {
    
    @StateObject var location = Location()
    @StateObject var places = Places()
    @State var index = 0
    
    var body: some View {
        NavigationView{
            List{
                ForEach (places.allPlaces, id: \.self) { _ in
                    Text(incrementIndex())
                }
            }
        }
        .navigationTitle("All Places")
    }
    
    func incrementIndex() -> String{
        index += 1
        print(index)
        return  (places.getPlaces(PlaceNumber: index)[0])
    }
}

但当我开始这个时,控制台中的“打印(索引)”计数为无穷大,甚至不会加载视图。当我删除“index+=1”时,循环会像应该的那样打印数组的第一个元素25次。

我不想在列表中包含[[字符串]]的第一个元素,这就是为什么我从索引0开始,然后先递增。

你知道为什么会发生这种情况,以及如何阻止应用程序这样做吗?或者知道更好的增量方法?抱歉,如果描述得不好,请询问您是否有什么问题。

✅ 最佳回答:

incrementIndex()函数更新变量@State var index。这将导致视图re-render,然后再次调用incrementIndex()。这会导致无限循环。

目前,您没有使用ForEach provides函数参数,而是通过将其命名为_来丢弃它。我建议使用ForEach已经提供的值,而不是索引:

ForEach(places.allPlaces, id: \.self) { place in
    Text(place[0])
}