Picker with ForEach

I have a ForEach loop with Range that I use with Picker. I'm using Range because I want to set startYear and endYear when View appears. The following is my code.

import SwiftUI

struct ProviderCalendarView: View {
	@State private var startYear: Int = 2023
	@State private var endYear: Int = 2034
	@State private var selectedYear = 3

    var body: some View {
		VStack {
			HStack {

				Picker(selection: $selectedYear) {
					ForEach((startYear...endYear), id: \.self) { year in
						Text("\(year)")
					}
				} label: {

				}
			}
		}
    }
}

And the compiler says the following.

Picker: the selection "3" is invalid and does not have an associated tag, this will give undefined results.

It's not a critical error. But how can I stop it? Thanks.

Answered by Tomato in 762930022

The following works.

Picker(selection: $selectedYear) {
	ForEach(viewModel.years.indices, id: \.self) {
		Text("\(viewModel.years[$0])")
	}
} label: {

}
import SwiftUI

struct ProviderCalendarView: View {
	@StateObject var viewModel = YearViewModel()
	@State private var selectedYear = 3

    var body: some View {
		VStack {
			HStack {
				Picker(selection: $selectedYear) {
					ForEach(viewModel.years, id: \.self) { year in
						Text("\(year)")
					}
				} label: {

				}			
			}
		}
	}
}

class YearViewModel: ObservableObject {
	@Published var years: [Int] = []

	init() {
		createYears()
	}

	func createYears() {
		let now = Date()
		for i in 0..<4 {
			years.append(2023 + i)
		}
	}
}

I don't use Range to create an array in this case. Yet, I still get the same compiler guy.

Accepted Answer

The following works.

Picker(selection: $selectedYear) {
	ForEach(viewModel.years.indices, id: \.self) {
		Text("\(viewModel.years[$0])")
	}
} label: {

}
Picker with ForEach
 
 
Q