I’m trying to learn iOS swift UI development working through some of the Apple tutorials I came across this piece of code. I don’t understand how the onDelete modifier works. This may be more of a swift question than a specific swiftUI question but what’s confusing to me is the call to deleteMovies. The named parameter indexes: is blank. Obviously the parameter is being filled in, but what is the mechanism by which that happens? What is it even called when that happens?

Is there any Apple reference that describes this behavior?

import SwiftUI
import SwiftData


struct MovieList: View {
    @Query(sort: \Movie.title) private var movies: [Movie]
    @Environment(\.modelContext) private var context


    var body: some View {
        NavigationSplitView {
            List {
                ForEach(movies) { movie in
                    NavigationLink(movie.title) {
                        MovieDetail(movie: movie)
                    }
                }
                .onDelete(perform: deleteMovies(indexes:)) <<<—— ???
            }
            .navigationTitle("Movies")
            .toolbar {
                ToolbarItem {
                    Button("Add movie", systemImage: "plus", action: addMovie)
                }
            }
        } detail: {
            Text("Select a movie")
                .navigationTitle("Movie")
                .navigationBarTitleDisplayMode(.inline)
        }
    }


    private func addMovie() {
        context.insert(Movie(title: "New Movie", releaseDate: .now))
    }


    private func deleteMovies(indexes: IndexSet) {
        for index in indexes {
            context.delete(movies[index])
        }
    }
}


#Preview {
    MovieList()
        .modelContainer(SampleData.shared.modelContainer)
}

2 Replies 2

Pay close attention since it is a bit tricky:

.onDelete modifier is ASKING a function that takes IndexSet and returns Void.

deleteMovies actually IS a function that takes IndexSet and returns Void.

So you are passing the function itself as the argument of another function.

This is called higher-order function for your further research about how this mechanism works and this is the full documentation of Swift functions

I see. Thank you. I guess now that you explained it I sort of knew that. Thank you again.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.