Get the two foreach array the top one's index? - swift

is that a way to get the top parten foreach's index? by two using foreach array?
ForEach(total, id: \.id){ item in
ForEach(nameber, id: \.id){ item in
(get the total;s index)
}
}

very criptic question. Try this, to get the index and the item of the outer ForEach:
ForEach(Array(total.enumerated()), id: \.1) { index, item in
ForEach(member, id: \.id) { item2 in
Text(String(index) + " \(item)" + " \(item2)")
}
}

You need to give the content's input different variable names.
You have both of them as item, so if you have different names, you can access the outside variable - not just the inside one.
Example:
struct ContentView: View {
var body: some View {
ForEach(0 ..< 5) { i in
ForEach(0 ..< 5) { j in
Text("(i: \(i), j: \(j))")
}
}
}
}
Result:
Variables renamed to match your example (using implicit (id: \.id, assuming they conform to Identifiable):
struct ContentView: View {
var body: some View {
ForEach(total) { totalItem in
ForEach(nameber) { nameberItem in
Text("(totalItem: \(totalItem), nameberItem: \(nameberItem))")
}
}
}
}

Related

How to increment a state in a ForEach loop in SwiftUI?

I need to increment the genNum variable and pass it to another struct in a ForEach loop. My code is compiling properly but cannot preview it in the simulation as well as the canvas. Getting "cannot preview in this file". Another error I am getting is "RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)".
BSServiceConnectionErrorDomain (3):
==BSErrorCodeDescription: OperationFailed
import SwiftUI
#available(iOS 14.0, *)
struct CategoryView: View {
#State var genNum: Int = -1
var categories: [Int: [PokemonData]] {
Dictionary(
grouping: pokemonData,
by: { $0.generation }
)
}
var columns: [GridItem] = [
GridItem(.fixed(170)),
GridItem(.fixed(170))
]
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted(), id: \.self) { key in
CategoryCard(genNum: self.increment()) // <--- Having problem with this line
}
}
AllCard()
.padding(.horizontal, 15)
.padding(.bottom, 20)
}
.navigationTitle("Categories")
}
}
// Function to increment the state value
func increment() -> Int {
self.genNum += 1
let i = genNum
return i
}
}
If all you want to do is to pass values from 0 to count-1 to your CategoryCard() initializer, you can use the enumerated() function. That function takes an array as input and returns an array of tuples where the first item is an array index and the 2nd item is the the element from the original array.
This code, for example:
let array = ["zero", "one", "two", "three"]
array.enumerated().forEach { (index, string) in
print (index, string)
}
Outputs the following:
0 zero
1 one
2 two
3 three
So you could rewrite your code like this:
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted().enumerated(), id: \.self) { (index, key) in
CategoryCard(genNum: index) // <--- Having problem with this line
}
}
(Disclaimer: I haven't used SwiftUI yet, so I'm not totally clear on what ForEach is doing inside your LazyGrid)

Swift add a button that deletes row from list that uses a foreach loop

I have a list that has a foreach loop and in every row I want to make a delete button that deletes the row.
I have an array of structs
struct Lists{
var title : String
var id = UUID()
}
and the array
#State var list = [Lists]()
and this is the list
List{
ForEach(list, id : \.id ){ item in
NavigationLink(destination:DetailView(word:item.title)){
HStack {
Text(item.title)
Spacer()
Button(action: {
self.list.remove(at: 0)
}){
Text("×")
}
}
}
}
}
I have set the remove(at:0) zero because I don't know how to get the index in the for loop.
The list:
I usually think is easier to use a count number instead.. like this:
List {
ForEach(0..<list.count, id : \.self ){ index in
NavigationLink(destination:DetailView(word: list[index].title)){
HStack {
Text(list[index].title)
Spacer()
Button(action: {
self.list.remove(at: index)
}){
Text("×")
}
}
}
}
}

SwiftUI core data, grouped list fetch result

using core data im storing some airport and for every airport i'm storing different note
I have created the entity Airport and the entity Briefing
Airport have 1 attribute called icaoAPT and Briefing have 4 attribute category, descript, icaoAPT, noteID
On my detailsView I show the list all the noted related to that airport, I managed to have a dynamic fetch via another view called FilterList
import SwiftUI
import CoreData
struct FilterLIst: View {
var fetchRequest: FetchRequest<Briefing>
#Environment(\.managedObjectContext) var dbContext
init(filter: String) {
fetchRequest = FetchRequest<Briefing>(entity: Briefing.entity(), sortDescriptors: [], predicate: NSPredicate(format: "airportRel.icaoAPT == %#", filter))
}
func update(_ result : FetchedResults<Briefing>) ->[[Briefing]]{
return Dictionary(grouping: result) { (sequence : Briefing) in
sequence.category
}.values.map{$0}
}
var body: some View {
List{
ForEach(update(self.fetchRequest.wrappedValue), id: \.self) { (section : Briefing) in
Section(header: Text(section.category!)) {
ForEach(section, id: \.self) { note in
Text("hello")
/// Xcode error Cannot convert value of type 'Text' to closure result type '_'
}
}
}
}
}
}
on this view I'm try to display all the section divided by category using the func update...
but Xcode give me this error , I can't understand why..Cannot convert value of type 'Text' to closure result type '_'
fore reference I list below my detailsView
import SwiftUI
struct DeatailsView: View {
#Environment(\.managedObjectContext) var dbContext
#Environment(\.presentationMode) var presentation
#State var airport : Airport
#State var note = ""
#State var noteTitle = ["SAFTY NOTE", "TAXI NOTE", "CPNOTE"]
#State var notaTitleSelected : Int = 0
#State var notaID = ""
var body: some View {
Form{
Section(header: Text("ADD NOTE Section")) {
TextField("notaID", text: self.$notaID)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("add Note descrip", text: self.$note)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Picker(selection: $notaTitleSelected, label: Text("Class of Note")) {
ForEach(0 ..< noteTitle.count) {
Text(self.noteTitle[$0])
}
}
HStack{
Spacer()
Button(action: {
let nota = Briefing(context: self.dbContext)
nota.airportRel = self.airport
nota.icaoAPT = self.airport.icaoAPT
nota.descript = self.note
nota.category = self.noteTitle[self.notaTitleSelected]
nota.noteID = self.notaID
do {
try self.dbContext.save()
debugPrint("salvato notazione")
} catch {
print("errore nel salva")
}
}) {
Text("Salva NOTA")
}
Spacer()
}
}
Section(header: Text("View Note")) {
FilterLIst(filter: airport.icaoAPT ?? "NA")
}
}
}
}
thanks for the help
This is because you try to iterate over a single Briefing object and a ForEach loop expects a collection:
List {
ForEach(update(self.fetchRequest.wrappedValue), id: \.self) { (section: Briefing) in
Section(header: Text(section.category!)) {
ForEach(section, id: \.self) { note in // <- section is a single object
Text("hello")
/// Xcode error Cannot convert value of type 'Text' to closure result type '_'
}
}
}
}
I'd recommend you to extract the second ForEach to another method for clarity. This way you can also be sure you're passing the argument of right type ([Briefing]):
func categoryView(section: [Briefing]) -> some View {
ForEach(section, id: \.self) { briefing in
Text("hello")
}
}
Note that the result of your update method is of type [[Briefing]], which means the parameter in the ForEach is section: [Briefing] (and not Briefing):
var body: some View {
let data: [[Briefing]] = update(self.fetchRequest.wrappedValue)
return List {
ForEach(data, id: \.self) { (section: [Briefing]) in
Section(header: Text("")) { // <- can't be `section.category!`
self.categoryView(section: section)
}
}
}
}
This also means you can't write section.category! in the header as the section is an array.
You may need to access a Briefing object to get a category:
Text(section[0].category!)
(if you're sure the first element exists).
For clarity I specified types explicitly. It's also a good way to be sure you always use the right type.
let data: [[Briefing]] = update(self.fetchRequest.wrappedValue)
However, Swift can infer types automatically. In the example below, the data will be of type [[Briefing]]:
let data = update(self.fetchRequest.wrappedValue)

Add Button by id for SwiftUI inside ForEach using shorthand argument name $0

How to add Button inside the ForEach ? Works with Text but no luck with Button. Will like to make use of shorthand argument name $0
import SwiftUI
struct ContentView: View {
let emojiMoves = ["🗿", "🧻", "✂️"]
var body: some View {
HStack {
ForEach(emojiMoves, id: \.self) {
Text($0)
}
}
}
}
Something like this could work but I like the simplicity of $0
ForEach(0 ..< self.emojiMoves.count, id: \.self ) { number in
Button(action: {
self.emojiMoves[(number)]
})
}
You can try
ForEach(self.emojiMoves, id: \.self ) {
Button($0){
}
}

Get index in ForEach in SwiftUI

I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index
When I iterate through objects
ForEach(array, id: \.self) { item in
CustomView(item: item)
.tapAction {
self.doSomething(index) // Can't get index, so this won't work
}
}
So, I've tried another approach
ForEach((0..<array.count)) { index in
CustomView(item: array[index])
.tapAction {
self.doSomething(index)
}
}
But the issue with second approach is, that when I change array, for example, if doSomething does following
self.array = [1,2,3]
views in ForEach do not change, even if values are changed. I believe, that happens because array.count haven't changed.
Is there a solution for this?
Another approach is to use:
enumerated()
ForEach(Array(array.enumerated()), id: \.offset) { index, element in
// ...
}
Source: https://alejandromp.com/blog/swiftui-enumerated/
This works for me:
Using Range and Count
struct ContentView: View {
#State private var array = [1, 1, 2]
func doSomething(index: Int) {
self.array = [1, 2, 3]
}
var body: some View {
ForEach(0..<array.count) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}
Using Array's Indices
The indices property is a range of numbers.
struct ContentView: View {
#State private var array = [1, 1, 2]
func doSomething(index: Int) {
self.array = [1, 2, 3]
}
var body: some View {
ForEach(array.indices) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}
I usually use enumerated to get a pair of index and element with the element as the id
ForEach(Array(array.enumerated()), id: \.element) { index, element in
Text("\(index)")
Text(element.description)
}
For a more reusable component, you can visit this article https://onmyway133.com/posts/how-to-use-foreach-with-indices-in-swiftui/
I needed a more generic solution, that could work on all kind of data (that implements RandomAccessCollection), and also prevent undefined behavior by using ranges.
I ended up with the following:
public struct ForEachWithIndex<Data: RandomAccessCollection, ID: Hashable, Content: View>: View {
public var data: Data
public var content: (_ index: Data.Index, _ element: Data.Element) -> Content
var id: KeyPath<Data.Element, ID>
public init(_ data: Data, id: KeyPath<Data.Element, ID>, content: #escaping (_ index: Data.Index, _ element: Data.Element) -> Content) {
self.data = data
self.id = id
self.content = content
}
public var body: some View {
ForEach(
zip(self.data.indices, self.data).map { index, element in
IndexInfo(
index: index,
id: self.id,
element: element
)
},
id: \.elementID
) { indexInfo in
self.content(indexInfo.index, indexInfo.element)
}
}
}
extension ForEachWithIndex where ID == Data.Element.ID, Content: View, Data.Element: Identifiable {
public init(_ data: Data, #ViewBuilder content: #escaping (_ index: Data.Index, _ element: Data.Element) -> Content) {
self.init(data, id: \.id, content: content)
}
}
extension ForEachWithIndex: DynamicViewContent where Content: View {
}
private struct IndexInfo<Index, Element, ID: Hashable>: Hashable {
let index: Index
let id: KeyPath<Element, ID>
let element: Element
var elementID: ID {
self.element[keyPath: self.id]
}
static func == (_ lhs: IndexInfo, _ rhs: IndexInfo) -> Bool {
lhs.elementID == rhs.elementID
}
func hash(into hasher: inout Hasher) {
self.elementID.hash(into: &hasher)
}
}
This way, the original code in the question can just be replaced by:
ForEachWithIndex(array, id: \.self) { index, item in
CustomView(item: item)
.tapAction {
self.doSomething(index) // Now works
}
}
To get the index as well as the element.
Note that the API is mirrored to that of SwiftUI - this means that the initializer with the id parameter's content closure is not a #ViewBuilder.
The only change from that is the id parameter is visible and can be changed
For non zero based arrays avoid using enumerated, instead use zip:
ForEach(Array(zip(items.indices, items)), id: \.0) { index, item in
// Add Code here
}
I created a dedicated View for this purpose:
struct EnumeratedForEach<ItemType, ContentView: View>: View {
let data: [ItemType]
let content: (Int, ItemType) -> ContentView
init(_ data: [ItemType], #ViewBuilder content: #escaping (Int, ItemType) -> ContentView) {
self.data = data
self.content = content
}
var body: some View {
ForEach(Array(zip(data.indices, data)), id: \.0) { idx, item in
content(idx, item)
}
}
}
Now you can use it like this:
EnumeratedForEach(items) { idx, item in
...
}
ForEach is SwiftUI isn’t the same as a for loop, it’s actually doing something called structural identity. The documentation of ForEach states:
/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity.
This means we cannot use indices, enumerated or a new Array in the ForEach. The ForEach must be given the actual array of identifiable items. This is so SwiftUI can animate the rows around to match the data, obviously this can't work with indicies, e.g. if row at 0 is moved to 1 its index is still 0.
To solve your problem of getting the index, you simply have to look up the index like this:
ForEach(items) { item in
CustomView(item: item)
.tapAction {
if let index = array.firstIndex(where: { $0.id == item.id }) {
self.doSomething(index)
}
}
}
You can see Apple doing this in their Scrumdinger sample app tutorial.
guard let scrumIndex = scrums.firstIndex(where: { $0.id == scrum.id }) else {
fatalError("Can't find scrum in array")
}
The advantage of the following approach is that the views in ForEach even change if state values ​​change:
struct ContentView: View {
#State private var array = [1, 2, 3]
func doSomething(index: Int) {
self.array[index] = Int.random(in: 1..<100)
}
var body: some View {
let arrayIndexed = array.enumerated().map({ $0 })
return List(arrayIndexed, id: \.element) { index, item in
Text("\(item)")
.padding(20)
.background(Color.green)
.onTapGesture {
self.doSomething(index: index)
}
}
}
}
... this can also be used, for example, to remove the last divider
in a list:
struct ContentView: View {
init() {
UITableView.appearance().separatorStyle = .none
}
var body: some View {
let arrayIndexed = [Int](1...5).enumerated().map({ $0 })
return List(arrayIndexed, id: \.element) { index, number in
VStack(alignment: .leading) {
Text("\(number)")
if index < arrayIndexed.count - 1 {
Divider()
}
}
}
}
}
2021 solution if you use non zero based arrays avoid using enumerated:
ForEach(array.indices,id:\.self) { index in
VStack {
Text(array[index].name)
.customFont(name: "STC", style: .headline)
.foregroundColor(Color.themeTitle)
}
}
}
To get indexing from SwiftUI's ForEach loop, you could use closure's shorthand argument names:
#State private var cars = ["Aurus","Bentley","Cadillac","Genesis"]
var body: some View {
NavigationView {
List {
ForEach(Array(cars.enumerated()), id: \.offset) {
Text("\($0.element) at \($0.offset) index")
}
}
}
}
Results:
// Aurus at 0 index
// Bentley at 1 index
// Cadillac at 2 index
// Genesis at 3 index
P. S.
Initially, I posted an answer with a "common" expression that all Swift developers are used to, however, thanks to #loremipsum I changed it. As stated in WWDC 2021 Demystify SwiftUI video (time 33:40), array indices are not stable from \.self identity (key path).
ForEach(0 ..< cars.count, id: \.self) { // – NOT STABLE
Text("\(cars[$0]) at \($0) index")
}
Here is a simple solution though quite inefficient to the ones above..
In your Tap Action, pass through your item
.tapAction {
var index = self.getPosition(item)
}
Then create a function the finds the index of that item by comparing the id
func getPosition(item: Item) -> Int {
for i in 0..<array.count {
if (array[i].id == item.id){
return i
}
}
return 0
}
You can use this method:
.enumerated()
From the Swift documentation:
Returns a sequence of pairs (n, x), where n represents a consecutive
integer starting at zero and x represents an element of the sequence.
var elements: [String] = ["element 1", "element 2", "element 3", "element 4"]
ForEach(Array(elements.enumerated()), id: \.element) { index, element in
Text("\(index) \(element)")
}
Just like they mentioned you can use array.indices for this purpose
BUT remember that indexes that you've got are started from last element of array, To fix this issue you must use this: array.indices.reversed() also you should provide an id for the ForEach.
Here's an example:
ForEach(array.indices.reversed(), id:\.self) { index in }