2

I am still new to SwiftUI framework I am learning with HackingWithSwift for NavigationStack. I followed all the steps just one difference is my result of code. I ran without any error just like in video however I could not navigate to my Detail destination.

  struct ContentView: View {
   var destinations = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
   var body: some View {
    NavigationStack {
        List(destinations, id: \.self) { i in
            NavigationLink(value: i) {
                Label("Row \(i)", systemImage: "\(i).circle")
            }
        }
        .navigationDestination(for: Int.self) { i in
            Text("Detail \(i)")
        }
        .navigationTitle("Navigation")
     }
   }
  }

My simulator show a List of Rows with Labels but I am unable to navigate. Could this by chance a bug because this is still new. Thank you in advance.

Steven-Carrot
  • 2,368
  • 2
  • 12
  • 37

2 Answers2

2

Your List data is an array of String, but the .navigationDestination value type is Int.

To fix your problem, modify the data type of .navigationDestination like below:

.navigationDestination(for: String.self) { I in //modify here
        Text("Detail \(i)")
}
Steven-Carrot
  • 2,368
  • 2
  • 12
  • 37
1

There is special List (and ForEach) syntax for a static array of Int, here it is:

struct NavTestView: View {

  //let destinations = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]

  var body: some View {
   NavigationStack {
       List(1..<10) { i in
           NavigationLink(value: i) {
               Label("Row \(i)", systemImage: "\(i).circle")
           }
       }
       .navigationDestination(for: Int.self) { i in
           Text("Detail \(i)")
       }
       .navigationTitle("Navigation")
    }
  }
 }

If you move on to requiring a dynamic array, i.e. you add or remove items, you really shouldn't misuse the API with the id:\.self hack or it'll crash, you need to migrate to an array of struct that contains a property that is a unique identifier, even better conform the struct to Identifiable that provides an id property for List/ForEach to use automatically, e.g.

struct ListItem: Identifiable {
    let id = UUID()
    var number: Int
}
malhal
  • 26,330
  • 7
  • 115
  • 133