Let’s create a basic custom Item
type with a title and a date.
struct Item {
let title: String
let date: Date
}
Any SortDescriptor<Item>
conforms to Codable
out of the box. So the above code compiles perfectly.
do {
let descriptor = SortDescriptor<Item>(.title, comparator: .localizedStandard)
let encoded = try JSONEncoder().encode(descriptor)
print(String(data: encoded, encoding: .utf8)!)
} catch {
debugPrint(error)
}
However, the encoding fails at runtime.
Swift.EncodingError.invalidValue(Foundation.SortDescriptor<__lldb_expr_46.Item>.AllowedComparison.comparableString((extension in Foundation):Swift.String.StandardComparator(options: __C.NSStringCompareOptions(rawValue: 833), isLocalized: true, order: Foundation.SortOrder.reverse), Item.title), Swift.EncodingError.Context(codingPath: [], debugDescription: “Encoding SortDescriptor with values of type non-NSObject
Compared
is unsupported.”, underlyingError: nil))
Why does this happen?