Using shorthand syntax in context menus?

I am assuming there is a simple reason for this, but I'm stuck. If don't comment out os_log code, the below fails to compile. Is there a reason the $0 can't be used in the contextMenu?

import SwiftUI
import os.log

struct ContentView: View {
    
    var capitals = ["Kuala Lumpur", "Tokyo", "Canberra"]
    @State private var test: Bool = false
    
    var body: some View {
        VStack {
            ForEach(capitals, id: \.self, content: {
                Text($0)
                .contextMenu(menuItems: {
                    Button(action: {
                        //os_log(.info, "Capital selected: ", $0)
                        self.test.toggle()
                    }, label: {
                        Text("Hello!")
                        Image(systemName: "hand.raised.fill")
                    })
                })
            })
            
            Text(test ? "true" : "false")
            .padding()
        }
    }
}

The inner closures have no arguments, so you cannot use $0 to refer to ForEach's closure argument (even if it did, it will shadow the outer one).

What you want to do here is to explicitly provide a name for the ForEach closure's argument and then you can use it in the call to os_log:

ForEach(capitals, id: \.self, content: { capital in
  ...
  Button(action: {
    os_log(.info, "Capital selected: ", capital)
  ...
}
1 Like