swiftswiftuixcode12

Initialize @StateObject with a parameter in SwiftUI


I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an initializer.

To be more specific, this snippet of code works fine:

struct MyView: View {
  @StateObject var myObject = MyObject(id: 1)
}

But this does not:

struct MyView: View {
  @StateObject var myObject: MyObject

  init(id: Int) {
    self.myObject = MyObject(id: id)
  }
}

From what I understand the role of @StateObject is to make the view the owner of the object. The current workaround I use is to pass the already initialized MyObject instance like this:

struct MyView: View {
  @ObservedObject var myObject: MyObject

  init(myObject: MyObject) {
    self.myObject = myObject
  }
}

But now, as far as I understand, the view that created the object owns it, while this view does not.

Thanks.


Solution

  • Here is a demo of solution. Tested with Xcode 12+.

    class MyObject: ObservableObject {
        @Published var id: Int
        init(id: Int) {
            self.id = id
        }
    }
    
    struct MyView: View {
        @StateObject private var object: MyObject
        init(id: Int = 1) {
            _object = StateObject(wrappedValue: MyObject(id: id))
        }
    
        var body: some View {
            Text("Test: \(object.id)")
        }
    }
    

    From Apple (for all those like @user832):

    confirmation