SwiftUI, FetchedResults, and uninitliazed?

I've got

    @Environment(\.managedObjectContext) var context
    private var home: Home
    private var predicate: NSPredicate

    @State var sortBy: SortDescriptor<Room>
    @FetchRequest private var rooms: FetchedResults<Room>
    init(home: Home) {
        self.home = home
        _sortBy = State(initialValue: SortDescriptor<Room>(\.name))
        self.predicate = NSPredicate(format: "%K = %@", "home", self.home)
        _rooms = FetchRequest<Room>( sortDescriptors: [self.sortBy], predicate: self.predicate)
    }

But it won't compile -- it says Variable 'self.rooms' used before being initialized. But... how?

hi,

basically, you cannot use the properties of self on the right side of the assignments in the init() to initialize other properties of self ... it's a logical problem because self does not fully exist until all its properties are set.

right now, you attempt to set self.predicate using the value of self.home; and you try to set _rooms using the values of self.sortBy and self.predicate.

use a local variable or two, and rely on the incoming parameter as well:

init(home: Home) {
        self.home = home
        let descriptor = SortDescriptor<Room>(\.name)
        _sortBy = State(initialValue: descriptor)
        let myPredicate = NSPredicate(format: "%K = %@", "home", home) // note use of incoming parameter home, not self.home
        self.predicate = myPredicate
         _rooms = FetchRequest<Room>(sortDescriptors: [descriptor], predicate: myPredicate) // note use of local variables here
    }

hope that helps,

DMG

FWIW: i am curious as to why sortBy is marked as a @State property. this gives you the ability to change it, yes, but you'd also want to then also update the FetchRequest that relies on it.

I did eventually get it working, but it's annoying. The sort is an @State 'cause I am playing around and experimenting, which is why this particular failure was frustrating.

SwiftUI, FetchedResults, and uninitliazed?
 
 
Q