Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is firstIndex in SwiftUI - Swift

While following the Apple tutorial about SwiftUI I found this:

1| var landmarkIndex: Int {
2|    userData.landmarks.firstIndex(where: { $0.id == landmark.id })!
3| }

Inside the tutorial line 2 isn't explained so well, they only say: "You’ll use landmarkIndex when accessing or updating the landmark’s favorite status, so that you’re always accessing the correct version of that data."

I can't understand what is firstIndex and what I am accessing by writing "$0.id == landmark.id" Why am I creating this var?

Thank you so much - Nico

Apple tutorial about SwiftUI

like image 847
Vipera74 Avatar asked Nov 16 '25 00:11

Vipera74


1 Answers

If you were to write this verbosely it would look something like this:

var landmarks: [LandMark] = []
for l in userData.landmarks {
  if isLandMarkEqual(l, landmark) {
    landmarks.append(l)
  }
}

func isLandMarkEqual(_ landmarkOne: LandMark, _ landmarkTwo: LandMark) -> Bool {
  return landmarkOne.id == landmarkTwo.id
}

We are iterating over userData.landmarks and calling a function (denoted by the {}) on every element. We then get the index of the first occurrence of an element that meets the condition laid out in the function (also called a closure).

If we were to simply return true e.g.

userData.landmarks.firstIndex(where: { true })!

then the condition would be true for every element and therefore we would just get the first index in the collection aka 0.

$0 is simply shorthand for the first parameter in the function/closure. In our example this is equivalent to landmarkOne.

like image 185
Cameron Porter Avatar answered Nov 17 '25 20:11

Cameron Porter