2

I wanted to make a parent view model that contains some basic stuff that I want all my view models to have in SwiftUI. I'm trying to make the parent view model have a generic variables so I can inherit ParentViewModel in any view model I make with the custom type.

This is what I've tried and got a Cannot find type 'T' in scope error on the loaded case. Not really sure how I can make that generic, any insight here?

class ParentViewModel: ObservableObject {
    enum Status {
        case loading
        case loaded(T)
        case error(Error)
    }
    
    @Published var status: Status = .loading
}

class ChildViewModel: ParentViewModel {
    
    init() {
        self.status = .loading
    }
    
    init(object: SomeObject) {
        self.status = .loaded(object)
    }
}

1 Answer 1

2

When you use a generic, you have to declare it in <>, which is missing in your example.

Here's a modified version that works:

class SomeObject { }

class ParentViewModel<T>: ObservableObject { // Declare T
    enum Status {
        case loading
        case loaded(T)
        case error(Error)
    }
    
    @Published var status: Status = .loading
}

class ChildViewModel: ParentViewModel<SomeObject> { // Specify that ParentViewModel will use SomeObject as T
    
    override init() {
        self.status = .loading
    }
    
    init(object: SomeObject) {
        self.status = .loaded(object)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.