UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftData outside of View

Forums > Swift

@yaboi  

Ok, I get the whole idea of SwiftData is being tightly coupled to SwiftUI, but can it seriously not be decoupled AT ALL?!

I'm really struggling with the idea that I can't use SwiftData outside of a view, there are so many relevant scenarios that aren't in views. Some examples:

  • when a silent notification comes in, create and insert a model
  • search the datastore for a specific model
  • check the most recently updated model for more accurate refreshing
  • so many more reasons

So, has anyone found the proper way to access SwiftData outside of a view? Am I stupid?

4      

@yaboi  

I even tried doing this dumbness:

import SwiftData
import SwiftUI

struct SwiftDataInsertionView: View {
    @Environment(\.modelContext) var context
    var modelType: any PersistentModel

    init(modelType: any PersistentModel) {
        self.modelType = modelType
        let _ = insertToSD()
    }

    var body: some View {
        EmptyView()
    }

    func insertToSD() -> Bool {
        do {
            print("inserting to context")
            context.insert(modelType)
            try context.save()
        } catch {
            return false
        }
        return true
    }
}

It didn't work and crashed the app every time.

2      

I've created an account just say that I feel the same and understand the pain of seeing this tight coupling. Maybe Apple's direction is to make things easy for beginners and reduce the complexity to develop simple apps. If you try to make an enterprise app with complex logic I feel you have to fight the frameworks, which is such a shame and usually a red flag. Anyways, here is one interesting attempt https://github.com/shapehq/SwiftDataDecoupled by Simon. He mentioned it here https://mastodon.social/@simonbs/111006307806396677

I myself am looking also into a pragmatic solution for this problem. My hope is that more developers will join to find a way out. So far, I'm still using CoreData in my professional work with SwiftUI + MVVM + Clean Architecture.

Update: There is also a post regarding some separation https://www.hackingwithswift.com/quick-start/swiftdata/how-to-use-mvvm-to-separate-swiftdata-from-your-views But it's still coupled in the initializer with the context. But it's a step forward, although it's a shame to lose the Query property wrapper

   

How about using Core Data and Swift Data in the same app? Use Core Data for the methods outside a view.

See the (unfortuntely brief) topic "How to make Core Data and SwiftData coexist in the same app" in Paul's “Swift Data by Example” book.

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.