0

enter image description here

I have the following problem I have an array at the beginning empty []

Then later it will be filled if certain things happen.

Anyway, as soon as I start the program I get the following error.

Can anyone help me out?

@State var userArray = []

if(userArray.count > 0) {
   Picker("", selection: $user) {
          ForEach(userArray, id: \.self) {
            Text($0)
          }
   }.labelsHidden()
}

2
  • Does your userArray array hold and array of a custom class, or String? Commented Jul 9, 2021 at 16:20
  • Array of strings Commented Jul 9, 2021 at 16:22

1 Answer 1

1

Try explicitly stating what objects you will be storing in userArray, in your case change

@State var userArray = []

to

@State var userArray: [String] = []

or

@State var userArray = [String]()

If you don't explicitly state what you are going to store in a @State variable. Swift will automatically set the data type as Any

Refer the examples I have shown below. The first is before stating the data type, while the second is after I set the data type

  1. This is before explicitly stating what I will be storing on userArray enter image description here

  2. After explicitly stating that I will be storing an array of strings ([String])

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thx, but on the inside I had tried to do a similar thing if I remember Text($0 as! String) It tightened, but it didn't work.
Doing that would make it unnecessarily complex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.