每次点击随机化按钮时如何从 restaurantList 访问随机值

How do I access a random value from the restaurantList each time I tap the randomize button

struct RandomizeTab: View {
    
    var restaurantInfo = Restaurants()
    
    var body: some View {
        
        NavigationView {
            NavigationLink(
                destination: DetailView(restaurantInfo: restaurantInfo.restaurantList[Int.random(in: 0...restaurantInfo.restaurantList.count-1)]),
                label: {
                    Text("Randomize")
                        .font(.title3)
                        .fontWeight(.bold)
                        .padding()
                        .background(Color.red)
                        .foregroundColor(.white)
                        .clipShape(Capsule())
                })
            
        }

    }
}

目前,此代码会从列表中随机选择一家餐厅,而不会在我每次点击时从列表中随机选择一家新餐厅。

NavigationLink 目的地是在第一次渲染视图时计算的。所以,你的随机计算只会被调用一次。一种解决方案是使用 NavigationLink 延迟加载视图。我借用了一个 Whosebug 答案:()


struct ContentView : View {
    var elements = [1,2,3,4,5,6,7]
    
    var body: some View {
        NavigationView {
            NavigationLink(destination:
                            NavigationLazyView(DetailView(input: elements.randomElement()!))
            ) {
                Text("Go to random")
            }
        }
    }
}

struct NavigationLazyView<Content: View>: View {
    let build: () -> Content
    init(_ build: @autoclosure @escaping () -> Content) {
        self.build = build
    }
    var body: Content {
        build()
    }
}

struct DetailView : View {
    var input : Int
    
    var body: some View {
        Text("\(input)")
    }
}

现在,内容是延迟计算的,所以每次都是随机计算。