UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to pass a Component() from one array to another and reverse ?

Forums > SwiftUI

Hello everyone!

I have on Array that lists Component() I made; the list is predefined like this:

var collectionData = [
    Collectioncard(value: "1"),
    Collectioncard(value: "2"),
    Collectioncard(value: "reverse"),
    Collectioncard(value: "4",),
    Collectioncard(value: "strange"),
    Collectioncard(value: "6"),
    Collectioncard(value: "1")
]

And I want to pass the specific item I tap to another array (empty array):

var choosenData = [Choosencard]()

Here is what I declared in the top of my struct (and I have a class of type ObservableObject and @Published var in another swiftui file):

@State var collection = collectionData
@State var choosen = choosenData
@ObservedObject var collectionstore = CollectionStore()
@ObservedObject var choosenstore = ChoosenStore()

So I have a first loop for the "collection":

ForEach(collection.indices, id: \.self) { index in
        Component(myValue: self.collection[index].value)

        .onTapGesture {
                self.choosenstore.choosencard.append(
                    Choosendeck(value: self.collection[index].value)
                )
        }
}

And I have the second loop for the "choosen" one:

ForEach(choosenstore.choosencard) { choosen in
        Component(myValue: choosen.value)
}

And this work perfectly: the card I tap form the first list appears in the second list BUT I want to be able to add a TapGesture to this second ForEach to be able to reverse the Component: to put it back to the first array.

So I tried to modify the second loop like this:

ForEach(choosen.indices, id: \.self) { index in
        Component(myValue: self.choosen[index].value)
}

And this doesn't work and I have no idea why. It's the same construction as the first loop, so I should be ok, and if I try to prepopulate the empty array var choosenData = [Choosencard]() with some content, the predefined content appear.

I don't know what's wrong...

Any idea ?

Thanks in advance

2      

Still didn't manage to find the problem :/

Any ideas ?

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.