Search code examples
swiftinitializerswiftdata

Correct way to write a @model in swiftdata


I'm working on a Swift project where I have two model classes: PlaylistGroup and PlaylistItem. I'm running into an issue where I can't append items to the playlistItems property in PlaylistGroup. Below are the model definitions:

@Model
class PlaylistGroup  {
    @Attribute(.unique) var groupNumberID = UUID()
    var groupName: String
    var playlistModel: PlayListModel?
    
    @Relationship(deleteRule: .cascade, inverse: \PlaylistItem.group)
    var playlistItems: [PlaylistItem]?
    
    init(groupName: String) {
        self.groupName = groupName
        self.playlistItems = playlistItems. // should I write this??
    }
   
}

@Model
class PlaylistItem: Hashable {
    
    var duration: Int?
    var tvgId: String?
    var tvgName: String?
    var tvgCountry: String?
    var tvgLanguage: String?
    var tvgLogo: String?
    var tvgChno: String?
    var tvgShift: String?
    var groupTitle: String
    var seasonNumber: Int?
    var episodeNumber: Int?
    var kind: String?
    var url: URL?
    var lastPlay: Date
    
    var group: PlaylistGroup?
    
    init( duration: Int? = nil, tvgId: String? = nil, tvgName: String? = nil, tvgCountry: String? = nil, tvgLanguage: String? = nil, tvgLogo: String? = nil, tvgChno: String? = nil, tvgShift: String? = nil, groupTitle: String, seasonNumber: Int? = nil, episodeNumber: Int? = nil, kind: String? = nil, url: URL? = nil, lastPlay: Date) {
        
        self.duration = duration
        self.tvgId = tvgId
        self.tvgName = tvgName
        self.tvgCountry = tvgCountry
        self.tvgLanguage = tvgLanguage
        self.tvgLogo = tvgLogo
        self.tvgChno = tvgChno
        self.tvgShift = tvgShift
        self.groupTitle = groupTitle
        self.seasonNumber = seasonNumber
        self.episodeNumber = episodeNumber
        self.kind = kind
        self.url = url
        self.lastPlay = lastPlay
    }
   
}



Should I initialize the playlistItems property in the PlaylistGroup initializer with self.playlistItems = playlistItems? I noticed that without this, I'm unable to append data to playlistItems using the append method. Any help would be greatly appreciated!

Thank you!


Solution

  • You could initialize it with an empty array. That way it's not nil (the default) and you should be able to append to it.

    Before adding playlistItems be sure to insert your PlaylistGroup into a model context.

    It's possible to this in the initializer:

    @discardableResult
    init(
        _ name: String,
        _ playlistItems: [PlaylistItem],
        insertInto context: ModelContext
    ) {
        self.groupName = name
        
        context.insert(self)
        self.playlistItems = playlistItems
    }