'How to limit the number of results in a FetchRequest in SwiftUI

How can I limit the size of the retrieved FetchedResults when making a FetchRequest to CoreData?

struct ContentView: View {
    var fetchRequest:FetchRequest<Kana>

    init(){
        fetchRequest = FetchRequest<Kana>(entity: Kana.entity(), sortDescriptors: [], predicate: NSPredicate(format: "alphabet == %@", "hiragana"))
    }

    var body: some View {
        List{
            Text("10 Kanas")
            // Display 10 Kanas
        }
    }
}



Solution 1:[1]

You need to create FetchRequest with NSFeatchRequest using corresponding initialiser, as shown below

init() {
    let request: NSFetchRequest<Kana> = Kana.fetchRequest()
    request.fetchLimit = 10
    request.predicate = NSPredicate(format: "alphabet == %@", "hiragana")
    fetchRequest = FetchRequest<Kana>(fetchRequest: request)
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1