Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Using different property wrappers for the same variable

Tags:

ios

swift

swiftui

in iOS13 I do the following to bind my View to my model:

class MyModel: ObservableObject {
    @Published var someVar: String = "initial value"
}

struct MyView: View {
    @ObservedObject var model = MyModel()
    
    var body: some View {
        Text("the value is \(model.someVar)")
    }
}

in iOS14 there is a new property wrapper called @StateObject that I can use in the place of @ObservedObject, I need this snippet of code to be compatible with iOS13 and iOS14 while leveraging iOS14's new feature, how can I do that with @StateObject for the same variable ?

like image 309
JAHelia Avatar asked May 21 '26 17:05

JAHelia


1 Answers

Different property wrappers generate different types of hidden properties, so you cannot just conditionally replace them. Here is a demo of possible approach.

Tested with Xcode 12 / iOS 14 (deployment target 13.6)

struct ContentView: View {
    var body: some View {
        if #available(iOS 14, *) {
            MyNewView()
        } else {
            MyView()
        }
    }
}

class MyModel: ObservableObject {
    @Published var someVar: String = "initial value"
}

@available(iOS, introduced: 13, obsoleted: 14, renamed: "MyNewView")
struct MyView: View {

    @ObservedObject var model = MyModel()

    var body: some View {
        CommonView().environmentObject(model)
    }
}

@available(iOS 14, *)
struct MyNewView: View {

    @StateObject var model = MyModel()

    var body: some View {
        CommonView().environmentObject(model)
    }
}

struct CommonView: View {
    @EnvironmentObject var model: MyModel

    var body: some View {
        Text("the value is \(model.someVar)")
    }
}
like image 55
Asperi Avatar answered May 23 '26 07:05

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!