This is my Group+CoreDataProperty. I am currently sorting alphabetically with postName. Now I want to sort by date added. how do I change this?
extension Group {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Group> {
return NSFetchRequest<Group>(entityName: "Group")
}
@NSManaged public var groupThumbnail: Data?
@NSManaged public var groupTitle: String?
@NSManaged public var home: Home?
@NSManaged public var posts: NSSet?
public var postsArr: [Post] {
let set = posts as? Set<Post> ?? []
return set.sorted {
$0.postName ?? "" < $1.postName ?? ""
}
}
}
I have tried to replace $0.postName ?? "" < $1.postName ?? "" with:
$0.postDate ?? "" < $1.postDate ?? "". But what do I replace "" with?
Thanks for any help!
If postDate
is of type Date
you can do
$0.postDate ?? Date() < $1.postDate ?? Date()
The value after ?? defines what is used when the primary value is nil
, so it always has to match the type of the original attribute. When String
it has to be a string, e.g. ""
, when Date it has to be a Date. Date()
would return the current date if the value is nil
– which shouldn't be the case anyway.