I’m defining a variable, ‘currentItem’ as a published object inside a class that conforms to ObservableObject (very last line in the code below).
struct Periodical: Codable, Identifiable
{
var id: UUID = UUID()
let name: String // name of the periodical
let dueDate: Date // due date
let price: Double? // price paid for the subscription
let notes: String // any comments
var dateExpired: Bool // Is the current date at or past due date?
{
let expired = dueDate < Date()
let isToday = Calendar.current.isDateInToday(dueDate)
return expired || isToday
}
enum CodingKeys: String, CodingKey
{
case id
case name
case dueDate = "expirationDate"
case price
case notes
}
}
class Periodicals: ObservableObject
{
static let itemKey = "Items"
var bypassDidSet = false // Prevent endless didSet loop.
@Published var items = [Periodical]()
{
didSet
{
if !bypassDidSet
{ save() }
}
}
@Published var currentItem: Periodical?
Notice that ‘items’ is also @Published.
When I try to declare it in a view, I get this error:
Generic struct ‘EnvironmentObject’ requires that ‘Periodical?’ conform to ‘ObservableObject’
struct ItemRow: View
{
@EnvironmentObject var periodicals: Periodicals
@EnvironmentObject var currentItem: Periodical? // error here
Notice that I don’t get the same error for ‘periodicals’ which was also defined as @Published in the same class.
Any advice?