Is it possible to replicate @State or @FetchRequest behaviour?

I mean: if I would like to create a property wrapper similar to @FetchRequest but using a different underlaying data source, will it be possible?

Or in a more concrete way: how can I send a state change from my own property wrapper so the view hierarchy is updated as response?

Answered by OOPer in 687355022

Or in a more concrete way: how can I send a state change from my own property wrapper so the view hierarchy is updated as response?

Maybe you can achieve what you want using DynamicProperty.

A simplified example:

import SwiftUI

struct ContentView: View {
    @Delay(seconds: 3) var value
    
    var body: some View {
        VStack {
            Text("\(value)")
                .padding()
            Button("add delayed") {
                value += 1
            }
        }
    }
}

@propertyWrapper struct Delay: DynamicProperty {
    @State var value: Int = 0
    let seconds: Int
    
    var wrappedValue: Int {
        get {
            value
        }
        nonmutating set {
            DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(seconds)) {
                self.value = newValue
            }
        }
    }
}

Or this article might be a good example:

https://www.hackingwithswift.com/plus/intermediate-swiftui/creating-a-custom-property-wrapper-using-dynamicproperty

Accepted Answer

Or in a more concrete way: how can I send a state change from my own property wrapper so the view hierarchy is updated as response?

Maybe you can achieve what you want using DynamicProperty.

A simplified example:

import SwiftUI

struct ContentView: View {
    @Delay(seconds: 3) var value
    
    var body: some View {
        VStack {
            Text("\(value)")
                .padding()
            Button("add delayed") {
                value += 1
            }
        }
    }
}

@propertyWrapper struct Delay: DynamicProperty {
    @State var value: Int = 0
    let seconds: Int
    
    var wrappedValue: Int {
        get {
            value
        }
        nonmutating set {
            DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(seconds)) {
                self.value = newValue
            }
        }
    }
}

Or this article might be a good example:

https://www.hackingwithswift.com/plus/intermediate-swiftui/creating-a-custom-property-wrapper-using-dynamicproperty

Is it possible to replicate @State or @FetchRequest behaviour?
 
 
Q