How to give default value to TableColumn in Table

I have this sample code:

struct Item: Identifiable {
    var id = UUID()
    var name: String?
}

struct ItemTable: View {
    
    let items: [Item]
    
    var body: some View {
        Table(items) {
            TableColumn("Name", value: \.name)
        }
    }
}

I get the following error:

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

I can solve using \.name!, but I'd like to give a default value instead (something like \.name ?? "default").

How can I achieve this?

Answered by P222PJP in 691987022

You could do it using the below.

Table(items) {
    TableColumn("Name") { item in
        Text(item.name ?? "Default Value")
    }
}

One possible solution would be adding a computed property:

extension Item {
    var nameDefaulted: String {name ?? "default"}
}

struct ItemTable: View {
    
    let items: [Item]
    
    var body: some View {
        Table(items) {
            TableColumn("Name", value: \.nameDefaulted)
        }
    }
}

You could declare your struct like this:

struct Item: Identifiable {
    var id = UUID()
    var name: String = "DefaultValue"
}

struct ItemTable: View {
    
    let items: [Item]
    
    var body: some View {
        Table(items) {
            TableColumn("Name", value: \.name)
        }
    }
}
Accepted Answer

You could do it using the below.

Table(items) {
    TableColumn("Name") { item in
        Text(item.name ?? "Default Value")
    }
}
How to give default value to TableColumn in Table
 
 
Q