NEW: Learn to build the incredible iOS 15 Weather app today! >>

How to allow row selection in a list

Paul Hudson    @twostraws   

Updated for Xcode 13.2

SwiftUI’s lists support both single and multiple selection of its items, but only when your list is in editing mode.

To support single selection, first add an optional property of the same type you’re using inside your list. For example, if you were using a list of integers you would have an optional Int. Once you have that, pass it to your list using its selection parameter, then make sure your list is in editing mode.

As an example, this code shows an array of strings in a list, and stores the selected item as an optional string:

struct ContentView: View {
    @State private var selection: String?

    let names = [

    var body: some View {
        NavigationView {
            List(names, id: \.self, selection: $selection) { name in
            .navigationTitle("List Selection")
            .toolbar {

Download this as an Xcode project

Notice that edit button in the toolbar – remember, your list must be in editing mode to support selection.

If you want multiple selection, all you need to do is change your selection property into a Set of the same type as your list array. So, if we wanted multiple selection in the previous example we’d use this:

@State private var selection = Set<String>()

Tip: Both the single and multiple selection options can be changed by you programmatically, allowing you to change which rows were selected by modifying the state yourself.

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

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

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.5/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.