1

I'm working on my first SwiftUI project and am running into an issue with ObservableObject that I'm at a loss for. The following is a simplified version of my code that reproduces the issue:

import Foundation

protocol ObjectProtocol: ObservableObject {
    var value: String { get }
}

class Object: ObjectProtocol {
    @Published private(set) var value: String

    init(value: String) {
        self.value = value
    }
}

and my content view:

import SwiftUI

struct ContentView: View {
    @ObservedObject var object: Object

    var body: some View {
        VStack {
            Text(object.value)
        }
    }
}

When I run this, I get the error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x104465d48)" at the "Text(object.value)" line of ContentView. Interestingly, though, the error no longer occurs and it runs as expected when I change ObjectProtocol to:

protocol ObjectProtocol: ObservableObject {
    // var value: String { get }
}

Does anyone have an idea as to what is causing this? Is this a bug with SwiftUI/ObservableObject, or am I misunderstanding something?

(running on iOS 13.0, Swift 5, Xcode 11.3.1)

liam923
  • 991
  • 1
  • 10
  • 19
  • It may be because `@Published` properties are not yet compatible with protocols yet. This is similar to [this](https://stackoverflow.com/a/57657870/9607863) question (not duplicate or anything though). They say: `"This is because property wrapper declarations get synthesized into three separate properties at compile-time, and this would not be appropriate for an abstract type."` – George Mar 02 '20 at 00:17
  • With Xcode 11.2 / iOS 13.2 works fine. I just set for testing `@ObservedObject var object = Object(value: "Test")`. Variant with `ContentView(object: Object(value: "Test"))` also works, and in Preview and in Simulator. – Asperi Mar 02 '20 at 06:31

0 Answers0