I'm using a DatePicker to store the selected date in Core Data in the format string and so I used a computed property that returns a String and uses a DateFormatter that accepts a type date to be converted in string.
I have another view which fetches the stored date of type string from CoreData.
So, to convert that string date to type Date to be fetched in the date picker I created a computed property that returns a type Date and using dateFormatter I convert the fetched date of type String to type Date.
The picker requires a Binding Date and I'm following MVVM so I've a ExistingDealDetailsViewModel from where I'm accessing dealClosingDate.
But the compiler gives me the Error: "Cannot assign to property: 'selectedDealClosingDate' is a get-only property".
Requirement/Goal: I want to retrieve the stored date and display it in the DatePicker as the selected date.
All and any sort of help is appreciated, thank you.
ExistingDealsView:
VStack {
Text("Deal Closing Date")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
DatePicker("Select a date:", selection: $existingDealDetailsVM.selectedDealClosingDate, displayedComponents: [.date]) //Error is shown at this line
.padding()
.overlay(RoundedRectangle(cornerRadius: 0)
.stroke(lineWidth: 1)
.foregroundColor(.gray))
.datePickerStyle(.compact)
}
.padding()
ExistingDealDetailsViewModel:
import SwiftUI
class ExistingDealDetailsViewModel: ObservableObject {
@Published var toggle: Bool = false
func update(){
CoreDataManager.shared.save()
}
var deal = Deal() // Deal is a CoreData Entity Class
var dateFormatter = DateFormatter()
var selectedDealClosingDate: Date {
var dealClosingDate = deal.dealClosingDate //dealClosingDate is of type String
dateFormatter.dateFormat = "dd/MM/YY"
return dateFormatter.date(from: dealClosingDate) ?? Date.now
}
}
CodePudding user response:
Think about what happens when the user changes the selection using the date picker - you would want selectedDealClosingDate to be set to the newly selected value, don't you? But look at the way you have declared selectedDealClosingDate! You've only defined how to compute its value, but not how to set its value.
var selectedDealClosingDate: Date {
var dealClosingDate = deal.dealClosingDate
dateFormatter.dateFormat = "dd/MM/YY"
return dateFormatter.date(from: dealClosingDate) ?? Date.now
}
You should add a setter:
var dateFormatter = {
let formatter = DateFormatter()
formatter = .dateFormat = "dd/MM/yy"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
var selectedDealClosingDate: Date {
get {
var dealClosingDate = deal.dealClosingDate
return dateFormatter.date(from: dealClosingDate) ?? Date.now
}
set {
deal.dealClosingDate = dateFormatter.string(from: newValue)
}
}
Also, I find it a bit weird that you are storing a deal closing date in Core Data as a string. You might want to reconsider that.
