I am doing a bar chart in my SwiftUI app, however I encountered a problem...
struct ViewMonth: Identifiable {
let id = UUID()
let date: Date
let viewCount: Int
}
I defined several variable types in the above code.
struct Date {
static func from(year: Int, month: Int, day: Int) -> Date {
let components = DateComponents(year: year, month: month, day: day)
return Calendar.current.date(from: components)!
}
}
It seems like I can't convert the expression type 'Foundation.Date' to 'BarCharts.Date'. I don't understand the error message. Please help!
I expect the code will yield no errors.
CodePudding user response:
The error complains about a terminology conflict of your type Date
with existing Date
in Foundation
.
Basically there are three options:
- Replace
struct Date
withextension Date
. - Rename your struct
Date
as something which does not interfere with any type in theFoundation
framework. - Declare all instances of your custom type as
BarCharts.Date
.
I recommend the first option.
CodePudding user response:
There are two types: Foundation.Date is the date type that everyone uses. And I suppose you defined your struct Date inside a class Barcharts, so it is a Barcharts.Date.
The “from” function is declared to return Date - which is a shortcut for Barcharts.Date. Now the error message should make sense. It’s up to you to decide what you wanted it to return.