I am trying to follow the Model View ViewModel format for SwiftUI, but am running into an issue with UUID. I have an object of type TimeCode
that has an attribute id
of type UUID (TimeCode
is created in xcdatamodels as a CoreData model). In order to create a TimeCodeViewModel
object, I need to assign the id
attribute in TimeCodeViewModel
with the same UUID from the original TimeCode
object. I therefore created this class definition to do so:
class TimeCodeViewModel: Identifiable {
var id: UUID
var fullName = ""
init(timeCode: TimeCode) {
self.id = timeCode.id
self.fullName = timeCode.fullName
}
// class methods
}
However, I get a compile time error saying that UUID is a get-only property. This makes sense, since you shouldn't be able to reassign the unique ID of an object to a different object, but in this case I am actually trying to describe the same object. Is it possible to assign self.id
with the same UUID?
I guess another approach could be to make the UUID a string and then assign it to the view model, but is it then possible to convert the string back into a UUID? For example, I want to fetch the original TimeCode
from CoreData using the UUID from the TimeCodeViewModel
so I can save edits to other attributes of the TimeCode
.
It would be interesting to see how the TimeCode Class looks like. I don't think that the id is set correctly. If you want a unique identifier as a String add the following to generate one:
var id: String = UUID().uuidString
You can share the string and therefore reference to the same object.
EDIT: Regarding the new information, changing the class to the following might be an idea:
class TimeCodeViewModel: Identifiable {
var id: UUID {
return timeCode.id
}
var fullName = ""
private var timeCode: TimeCode
init(timeCode: TimeCode) {
self.timeCode = timeCode
self.fullName = timeCode.fullName
}
// class methods
}