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)
}
}
CodePudding user response:
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> { // Specific that ParentViewModel will use SomeObject as T
override init() {
self.status = .loading
}
init(object: SomeObject) {
self.status = .loaded(object)
}
}