20

I would like to have a numbered list, where every row has a number.

Something like this

but I don't see right API for that in List initialisers

At this moment I see this workaround

var persons = ["Boris", "Anna", "Tom"]

// MARK: - Body
func body(props: Props) -> some View {
    List(persons.indices, id: \.self) { index in
        Text("\(index) \(self.persons[index])")
    }
}
Tikhonov Aleksandr
  • 13,945
  • 6
  • 39
  • 53

3 Answers3

20

Using .indices() is not a workaround, it is a proper way of doing it.

Alternatively, you can also use the code in the release notes for an indexed() array:

struct ContentView: View {
    var persons = ["Boris", "Anna", "Tom"]

    var body: some View {
        VStack {
            List(persons.indexed(), id: \.1.self) { idx, person in
                Text("\(idx) - \(person)")
            }
        }
    }
}


// This is taken from the Release Notes, with a typo correction, marked below
struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
    typealias Index = Base.Index
    typealias Element = (index: Index, element: Base.Element)

    let base: Base

    var startIndex: Index { base.startIndex }

   // corrected typo: base.endIndex, instead of base.startIndex
    var endIndex: Index { base.endIndex }

    func index(after i: Index) -> Index {
        base.index(after: i)
    }

    func index(before i: Index) -> Index {
        base.index(before: i)
    }

    func index(_ i: Index, offsetBy distance: Int) -> Index {
        base.index(i, offsetBy: distance)
    }

    subscript(position: Index) -> Element {
        (index: position, element: base[position])
    }
}

extension RandomAccessCollection {
    func indexed() -> IndexedCollection<Self> {
        IndexedCollection(base: self)
    }
}
kontiki
  • 37,663
  • 13
  • 111
  • 125
  • I tried but it didn't worked for me, build fails and no error was popped up ... – Najam Jan 24 '20 at 10:44
  • 2
    @kontiki, yes, it works, but I got a error "Type '_' has no member '1'" when I add if condition in List/ForEach. – foolbear Feb 16 '20 at 09:01
12

You can just use enumerated, for example https://github.com/onmyway133/blog/issues/515

struct CountriesView: View {
    let countries: [Country]

    var body: some View {
        let withIndex = countries.enumerated().map({ $0 })

        return List(withIndex, id: \.element.name) { index, country in
            NavigationLink(
                destination: CountryView(country: country),
                label: {
                    VStack(alignment: .leading) {
                        Text(country.name)
                            .styleMultiline()
                    }
                    .paddingVertically()
                }
            )
        }
    }
}
onmyway133
  • 45,645
  • 31
  • 257
  • 263
3

It's Apple example:

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

For You:

var persons = ["Boris", "Anna", "Tom"]

// MARK: - Body

func body(props: Props) -> some View {
List(persons.indices, id: \.self) { index in

var i: Int {
persons.firstIndex(where: { $0.id == index.id })!}

    Text("\(i) \(self.persons[i])")
}}
  • 1
    Trying to create the computed property inside the `List` as you did and I got ```Cannot declare local computed variable in result builder``` – David.C Apr 28 '22 at 22:12