Swift UI Preview for Multiple Entity

Hello,

I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview.

/// Entity data for use with canvas previews.
static var preview: Entity1 {
        let entities1 = Entity1.makePreviews(count: 1)
        return entities1[0]
}

@discardableResult
static func makePreviews(count: Int) -> [Entity1] {
        var contents = [Entity1]()
        let viewContext = PersistenceController.preview.container.viewContext
        let persistenceController = PersistenceController.shared
        for index in 0..<count {
            let entities1 = Entity1(context: viewContext)
            entities1.id = UUID()
            entities1.title = "Amazing day!"
            let photo = Photo(context: viewContext)
            let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()
            photo.linkedToJournal = journal
            let thumbnail = Thumbnail(context: viewContext)
            let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)
            thumbnail.data = thumbnailData
            thumbnail.photo = photo
            let photoDataObject = PhotoData(context: viewContext)
            photoDataObject.data = imageData
            photoDataObject.photo = photo
            contents.append(entities1)
        }
        return contents
}

You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview.

Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!

Answered by kaviraja in 770061022

Found a solution! Can refer to sample code here for solution: https://developer.apple.com/documentation/coredata/adopting_swiftdata_for_a_core_data_app to use multiple entity and to preview your UI in XCode Canvas.

Accepted Answer

Found a solution! Can refer to sample code here for solution: https://developer.apple.com/documentation/coredata/adopting_swiftdata_for_a_core_data_app to use multiple entity and to preview your UI in XCode Canvas.

Swift UI Preview for Multiple Entity
 
 
Q