KeyPathComparator and sorting with optional properties?

Is there any way to sort on key path to (or through) optional properties? I have this model:

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
}

And I would like to enable SwiftUI TableColumn sorting (via KeyPathComparator) through the optional executableInfo. I just want it to sort all the nil values together either all greater than or all less than any non-nil value. Unfortunately, I get compiler errors (or timeouts trying to compile) on the TableColumn(…,value:) using a key path through the optional executableInfo. so even if I could handle the sort comparison manually, I don’t know how to enable this.

KeyPathComparator has an init for keypaths that lead to optionals.

struct ProcessFile {
    var executableInfo: FileInfo?
}

struct FileInfo {
    var path: String
}

let comp = KeyPathComparator(\ProcessFile.executableInfo?.path)
var rcomp = comp; rcomp.order = .reverse

let files = [
    ProcessFile(),
    ProcessFile(executableInfo: .init(path: "xyz")),
    ProcessFile(executableInfo: .init(path: "abc")),
]

print(files.sorted(using: comp).map { $0.executableInfo?.path ?? "(nil)" }.joined(separator: ", "))
// output: (nil), abc, xyz
print(files.sorted(using: rcomp).map { $0.executableInfo?.path ?? "(nil)" }.joined(separator: ", "))
// output: xyz, abc, (nil)

If that's not working for you, can you post your attempt to use it, along with the compiler errors?

1 Like