I'm making a simple SwiftUI app with a sortable table. Everything seems fine until I try to make my table sortable by a Bool
property. The model looks like this:
struct ProcessFile : Codable
{
var id = UUID()
var label : String
var plistInfo : FileInfo
var executableInfo : FileInfo?
var executableExists : Bool { return self.executableInfo != nil }
}
struct FileInfo : Codable
{
var path : Path
var created : Date
var modified : Date
}
When I try to make a KeyPathComparator
using executableExists
, I get errors:
Model.swift:146:49: error: cannot convert value of type 'KeyPath<ProcessFile, Bool>' to expected argument type 'KeyPath<ProcessFile, Value?>'
self.tempFiles.sort(using: KeyPathComparator(\ProcessFile.executableExists))
^
Model.swift:146:49: note: arguments to generic parameter 'Value' ('Bool' and 'Value?') are expected to be equal
self.tempFiles.sort(using: KeyPathComparator(\ProcessFile.executableExists))
^
Model.swift:146:31: error: generic parameter 'Value' could not be inferred
self.tempFiles.sort(using: KeyPathComparator(\ProcessFile.executableExists))
^
Foundation.KeyPathComparator:6:12: note: in call to initializer
public init<Value>(_ keyPath: KeyPath<Compared, Value?>, order: SortOrder = .forward) where Value : Comparable
Relatedly, I get an error if I try to make one of the associated TableColumn
views use that Bool
property:
ContentView.swift:73:5: error: referencing initializer 'init(_:value:content:)' on 'TableColumn' requires that 'ProcessFile' inherit from 'NSObject'
TableColumn("", value: \.executableExists)
SwiftUI.TableColumn:4:11: note: where 'RowValue' = 'ProcessFile'
extension TableColumn where RowValue : NSObject, Sort == SortDescriptor<RowValue>, Label == Text {
^
ContentView.swift:73:5: error: referencing initializer 'init(_:value:content:)' on 'TableColumn' requires the types 'KeyPathComparator<ProcessFile>' and 'SortDescriptor<ProcessFile>' be equivalent
TableColumn("", value: \.executableExists)
SwiftUI.TableColumn:4:11: note: where 'Sort' = 'KeyPathComparator<ProcessFile>', 'SortDescriptor<RowValue>' = 'SortDescriptor<ProcessFile>'
extension TableColumn where RowValue : NSObject, Sort == SortDescriptor<RowValue>, Label == Text {
I see no reason why I shouldn’t be able to use a Bool
type here, and the docs even explicitly show methods for Bool
.