Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeGraph: cycle detected through attribute using @State in playgrounds

Tags:

ios

swift

swiftui

I'm trying to use SwiftUI's @State in playground. Here's my code:

import UIKit
import PlaygroundSupport
import SwiftUI

struct ContentView: View {
    @State private var showGreeting = false

    var body: some View {

        Form {
            Button(action: {
                self.showGreeting.toggle()
            }) {
                Text("Toggle Greeting")
            }

            if showGreeting {
                Text("Hello World!")
            }
        }
    }
}

let viewController = UIHostingController(rootView: ContentView())

PlaygroundPage.current.liveView = viewController

I can see the button on the live view. But if I click it, it doesn't show the text. A second click does reveal the text. Further clicks don't seem to make any difference visually.

On each click, I get the following message in log area:

=== AttributeGraph: cycle detected through attribute 38 ===

Need some help understanding what this means in this context and why the state is not behaving naturally.

Note: I'm running macOS Mojave, so I don't have option of SwiftUI previews. I'm making do with live preview of playgrounds.

like image 545
Akash Avatar asked Sep 28 '19 14:09

Akash


1 Answers

There's nothing wrong with your SwiftUI, and it runs fine when pasted into a new project.

If you change the Form to a VStack, it works fine in the playground. Using a List gives you the same error. Maybe a bug, I'd report it to Apple.

In my experience, if you're stuck on Mojave for the time being, just set up a project where you can run the simulator. It takes just a couple seconds to compile and run, and you wind up saving time when your SwiftUI playgrounds crash, get weird errors like this, etc.

like image 191
John M. Avatar answered Nov 10 '22 19:11

John M.