Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • 3
    I believe, that array.firstIndex(of: item) won't work if there are same elements in array, for example if array is [1,1,1], it will return 0 for all elements. Also, it is not very good performance to do this for each element of array. my array is a @State variable. @State private var array: [Int] = [1, 1, 2] Commented Jul 28, 2019 at 21:02
  • 60
    Never use 0..<array.count. Use array.indices instead. github.com/amomchilov/Blog/blob/master/… Commented Jul 28, 2019 at 21:33
  • 40
    Please note that the iOS 13 beta 5 release notes give the following warning about passing a range to ForEach: “However, you shouldn’t pass a range that changes at runtime. If you use a variable that changes at runtime to define the range, the list displays views according to the initial range and ignores any subsequent updates to the range.” Commented Jul 29, 2019 at 23:12
  • 3
    Thank you, Rob, that explains the array index out of bounds error generated by the above - my array's content changes over time. Problematic, as that essentially invalidates this solution for me. Commented May 18, 2020 at 20:19
  • 4
    developer.apple.com/videos/play/wwdc2021/10022 Using Index is not ideal if array content position can change like adding or removing content. As index is being used for implicit identification of views. We should explicitly set id modifier and use consistent id for same view Commented Jul 9, 2021 at 8:52