0

Question

I have the following ObservableObject and SwiftUI view.

class ExampleState: ObservableObject {}

struct ExampleView: View {
    @StateObject var state = ExampleState()

    var body: some View {
        EmptyView()
    }
}

And I want to pass state to the view from a UIKit view.

class ExampleViewController: UIViewController {
    var state = ExampleState()
    func test() -> some View {
        ExampleView(state: state) // A compile error occurs on this line
    }
}

But I got compile error on initializer calling. And the error message says "Reference to property 'state' in closure requires explicit use of 'self' to make capture semantics explicit"

First, I do not understand why this is closure.

Second, when I followed the error message and put self, a memory leak occurred. So could you tell me if I can make it weak reference.

Environment

  • iOS 16
  • Xcode 14.3.1

1 Answer 1

4

The weak reference is @ObservedObject

struct ExampleView: View {
    @ObservedObject var state : ExampleState

    var body: some View {
        EmptyView()
    }
}
  • Use @StateObject if the view owns the object.
  • Use @ObservedObject if the object is passed from another view or class.

But creating a SwiftUI view inside an UIViewController makes no sense. Interoperability between UIKit and SwiftUI must be performed with UIHostingView/UIHostingController and UIViewRepresentable

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.