user3574603
user3574603

Reputation: 3618

Swift: How do I update property when state property changes?

I have a collection of audio files.

I am displaying a collection of cover images for each episode using ACarousel that takes an index $currIndex.

I have a player object. It stores the current episode (player.currentEpisode = episode).

I can reference a particular episode from outside the carousel loop like so: player.episodes[currIndex].

I want to change player.currentEpisode every time currIndex updates: player.currentEpisode = player.episodes[currIndex]. I thought I could do this using didSet or willSet but it appears these aren't fired.

Why don't didSet or willSet fire? How can I update player.currentEpisode when currIndex updates?

struct ContentView: View {
    @EnvironmentObject var player: Player
    
    ...
    
    @State var currIndex: Int = 0 {
        didSet {
            print("Did set currIndex") // Nothing output to console
        }

        willSet {
            print("Will set currIndex") // Nothing output to console
        }
    }

    var body: some View {
        
        VStack {
            ACarousel(player.episodes, id: \.id, index: $currIndex, spacing: width/5, sidesScaling: 0.7, isWrap: true) { episode in
                    VStack {
                        Image(episode.image)
                    }
            }

    ...

Upvotes: 1

Views: 467

Answers (1)

Asperi
Asperi

Reputation: 257703

Use instead onChange(of: ), like

@State var currIndex: Int = 0

var body: some View {
    
    VStack {
        ACarousel(player.episodes, id: \.id, index: $currIndex, spacing: width/5, sidesScaling: 0.7, isWrap: true) { episode in
                VStack {
                    Image(episode.image)
                }
        }
        .onChange(of: currIndex) { [currIndex] newValue in // << here !!
           print("Old value: \(currIndex)")
           print("New value: \(newValue)")
        }

Upvotes: 1

Related Questions