I'm currently working on an App to manage Assignments, as I'm using different Types of Assignments like a To Do or a Homework, ... . So I made a Protocol for all key variables every Assignment should have, so that I can later display all different Types(conforming to Assignment) in one "All" List.
When testing in a Playground I managed to build a View which takes all Types conforming to Assignment and display title and description. But when starting in my main project I encountered these problems. Project Structure
a class Assignments holds all my data. Currently I have two lists with two types conforming to Assignment, HomeWork and OnlineLesson. This is just a transition and not good practise still...
a func getAll later should return both of those lists.
class Assignments: Storable, Codable, ObservableObject {
@Published var homeWorks: [HomeWork]
@Published var sortDescriptor: SortType
@Published var onlineLessons: [OnlineLesson]
func getAll<A: Assignment>() -> [A] {
var toReturn: [A] = []
toReturn.append(contentsOf: homeWorks as! [A])
toReturn.append(contentsOf: onlineLessons as! [A])
//I also don't understand why I have to cast the arrays as both types already conform to Assignment
return toReturn
}
}
This is the 'Assignment' protocol :
protocol Assignment: ObservableObject, Identifiable {
var title: String {get set}
var description: String {get set}
var createdAt: Date {get}
var dueTo: Date {get}
var type: AssignmentType {get set}
}
The View
struct AssignmentsAllView: View {
@EnvironmentObject var assignments: Assignments
...
}
@main
struct Homework_PlannerApp: App {
var assignments: Assignments = Assignments()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(assignments)
}
}
}
1st : Inside a List
ForEach(assigments.getAll()) {assigment in
//Unable to infer type of a closure parameter 'assigment' in the current context
// Generic parameter 'A' could not be inferred
}
2nd : When trying it without a list
Text(homeWorks.getAll().first!.title) //Generic parameter 'A' could not be inffered
Does someone know what I'm doing wrong, or how to fix this. As I'm new to protocols and I haven't enjoyed it so far to be honest.
Thanks for the Help, I got everything working by replacing the protocol Assignment, with an class Assignment:
class Assignment: ObservableObject {
@Published var title: String
@Published var description: String
@Published var createdAt: Date
@Published var dueTo: Date
let type: AssigmentType
init(title: String, description: String, dueTo: Date, type: AssigmentType) {
self.title = title
self.description = description
self.createdAt = Date()
self.dueTo = dueTo
self.type = type
}
}
The classes HomeWork and OnlineLesson now inherit from this super class...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.