iosarraysswiftxcodeswiftui

Array showing incorrect data in SwiftUI sheet


Here's the code

import SwiftUI

struct MyView: View {

@State private var Items = ["Apple", "Microsoft", "Google"]
@State private var presentSheet = Bool()

    var body: some View {
        NavigationStack {
            List {
                ForEach(Items) { item in 
                    Text(item)
                        .swipeActions(edge: .leading) {
                            Button("Show", systemImage: "eye" {
                                presentSheet.toggle
                            }
                            .tint(Color.yellow)
                        }

                    .sheet(isPresented: $presentSheet) {
                        Text(item)
                    }
                }
            }
            .navigationTitle("MyView")
        }
    }
}

The sheet only shows the last item in the array, when it should show the item that opened the sheet

I tried making a sheet view that only displays the text you selected

I was expecting it to show the single item, but instead just showed the last item in the array


Solution

  • Instead of presentSheet, use selectedItem to use .sheet(item: $selectedItem). I added the @MainActor annotation for safety reasons, and you should use it, too. If you compile it with Swift 6, you will get a warning that you should use @retroactive (SE-0364) to conform String to Identifiable.

    extension String: Identifiable {
        public var id: Self { self }
    }
    
    @MainActor
    struct MyView: View {
        @State private var items = ["Apple", "Microsoft", "Google"]
        @State private var selectedItem: String? = nil
        
        var body: some View {
            NavigationStack {
                List(items, id: \.self) { item in
                    Text(item)
                        .swipeActions(edge: .leading) {
                            Button("Show", systemImage: "eye") {
                                selectedItem = item
                            }
                            .tint(.yellow)
                        }
                }
                .navigationTitle("MyView")
                .sheet(item: $selectedItem) { string in
                    Text(string)
                }
            }
        }
    }