Swift UI TableColumn with Int data

I was playing around with TableColumn api in MacOS Ventura I have the following data model.

actor HousingData: Identifiable {
    let id: Int
    let rank: Int
    let region: String
    let regionType: RegionType
    let state: String
}

However when it try to do

TableColumn("foo", value: \.rank)

I get

Key path value type 'Int' cannot be converted to contextual type 'String'

if I try

TableColumn("Rank", value: \.rank) { rank in
    Text("\(rank)")
}

I get

Referencing initializer 'init(_:value:content:)' on 'TableColumn' requires the types 'Never' and 'KeyPathComparator<HousingData>' be equivalent

If i use a string value all works well.

I just saw in WWDC video you have to do:

TableColumn("Rank") { model in
      Text("\(model.rank)")
 }

Help documentation is deceiving.

Me2

Your first attempt without the content closure doesn't work because that version of the initializer only works for strings, as the last bit of the TableColumn overview mentions. The other version is almost correct, but it has to appear inside a Table that's been initialized with a sortOrder parameter. Also, the closure's parameter is a housing data item, not the rank property of a house data item. So something like this should work:

struct DataTable: View {
    @State private var sortOrder = [KeyPathComparator(\HousingData.rank)]

    var body: some View {
        Table(housingData, sortOrder: $sortOrder) {
            TableColumn("Rank", value: \.rank) { data in
                Text("\(data.rank)")
            }
        }
    }
}

Note that the only version which works is the one without the value parameter:

TableColumn("Rank") { model in
      Text("\(model.rank)")
 }

If you include the value, even if you also use the housing data item, you'll still get the KeyPathComparator error.

Swift UI TableColumn with Int data
 
 
Q