Using ForEach with a string array - [String] has n

2020-04-18 08:54发布

问题:

I'm using Xcode 11 beta 5 and what I had it doesn't work anymore. This is my code:

struct ModeView : View {
  @EnvironmentObject var state: IntentionState

  var body: some View {
      Picker(selection: $state.selection, label: Text("")) {
        ForEach(state.modes.identified(by: \.self)) { mode in
          Text(mode)
        }
      }.pickerStyle(SegmentedPickerStyle())
  }
}

The error is in the line ForEach(uistate.modes.identified(by: \.self)) { mode in and it says:

Value of type '[String]' has no member 'identified'

When I was using Xcode 11 beta 4 it worked perfectly. The question now is how to use ForEach with an array string in Xcode beta 5

回答1:

ForEach syntax changed a little bit in Beta 5.

Have you tried:

ForEach(state.modes, id: \.self) { mode in
    Text(mode)
}


回答2:

As per the apple release note, it's known issue from their end. We have to wait for another release.

https://developer.apple.com/documentation/ios_ipados_release_notes/ios_ipados_13_beta_5_release_notes



回答3:

The identified(by:) method has been deprecated, the correct syntax is now:

init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)

or after moving the content into a closure :

ForEach(state.modes, id: \.self) { mode in Text(mode) }


回答4:

let suppose you have a name array like this

let names = ["mike","Jack","jill"]

ForEach(names, id: .self) { Text($0) }

Text($0) - this will print all elements from your names array.

note** use backslashsign.self instead .self, somehow backslash sign is not working here.

This works. Thanks.



标签: swift swiftui