1

I have the following code:

import SwiftUI
func TableColumnView<T>(title: String? = nil, k : KeyPath<T, Int>) -> some TableColumnContent<T, KeyPathComparator<T>> where T:Identifiable{
    TableColumn(title ?? String(describing: k).components(separatedBy: ".").last!, value: k){ model in
                Text("\(model[keyPath: k])").padding(0)
    }.width(64)
}

struct Animal : Identifiable {
    var id : Int
    var a : Int
    var b : Int
    var c : Int
}

let animals : [Animal]=[Animal(id: 1, a:1,b:2,c:3),Animal(id: 2, a:4,b:5,c:6),Animal(id: 3, a:7,b:8,c:9)]
let keyPaths : [KeyPath<Animal, Int>] = [\Animal.a,\Animal.b,\Animal.c]

struct ContentView: View {
    @State var sortOrder: [KeyPathComparator<Animal>] = []

    var body: some View {
        VStack {
            Table(animals,sortOrder: $sortOrder){
                ForEach(keyPaths,id: \.self){ k in
                    TableColumnView(k: k)
                }
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

Now why do I get the error : Ambiguous use of 'init(_:id:content:)' on the ForEach? And how can I easily see the different possible uses? If I Command click on ForEach I only see one use. How can I see the others? And how do I solve it?

1 Answer 1

2

To have a dynamic number of table columns, you need to use TableColumnForEach, because TableColumnContent needs a bit more type information (namely RowValue and Sort) that a regular ForEach cannot provide.

Table(animals,sortOrder: $sortOrder){
    TableColumnForEach(keyPaths,id: \.self){ k in
        TableColumnView(k: k)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, 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.