Reputation: 411
I am trying to sort realm objects. The following code sorts allSongs correctly on title with the letters A-Z.
self.allSongs = realm.objects(Song.self).sorted("_title")
The thing is that I need to include Å, Ä and Ö (locale). The following code works. It sorts the songs correctly.
realm.objects(Song.self).sort {
$0.title.compare($1.title, locale: swedish) == .OrderedAscending
}
The problem is that I cannot assign the result to my array of songs. This line gives me an error: "Cannot assign result of type [Song] to type Results".
self.allSongs = realm.objects(Song.self).sort {
$0.title.compare($1.title, locale: swedish) == .OrderedAscending
}
Is there a way to cast it to the correct type?
Upvotes: 1
Views: 953
Reputation: 14409
Realm doesn't natively allow locale-sensitive sorting (see issue realm/realm-cocoa#2004). The sort you're using is an in-memory one defined by the Swift standard library (see SequenceType.sort()
) rather than the Realm one (see Results.sorted(_:)
).
You won't be able to re-assign or cast or convert a Swift.Array
to a RealmSwift.Results
.
If you want to benefit from Results
features like auto-updating and lazy loading, you'll need to store a normalized string on your model to sort by using Realm's sort. You could store both your normal string along with a "normalized" version in your data model, where you perform the case folding before storing the value in Realm, perhaps using CFStringTransform. You could then search on that string (also normalizing your search input).
Upvotes: 1