Fatal Error when updating @State var too frequently?

(I am using the Xcode 12 beta on macOS 11, for reference)

Hi, all. I am unsure if this is the right place to post this, but I hope it can help answer my question, as I am a little afraid of Stack Overflow :)

I am attempting to make a simple app for myself, and want to include a running counter of how many iterations a loop performs. I have an @State var String that is tied to a Text item in my UI, that in theory will update on every iteration of a loop. However, after a few iterations, it throws the error: "Thread 1: Fatal Error: Can't remove [first/last] element from an empty collection", as well as pointing me towards either line 841 or 617 of this Swift file.

Nowhere in my code do I call either removeFirst or removeLast on any collections, so I imagine that as part of clearing @State vars and redrawing the display, those end up being ran 'under the hood', as it were. Furthermore, the issue seems not to occur as frequently/if at all, when I use usleep() with values above ~3000. The issue also seems not to occur as often/if at all when I add a breakpoint to my @State var, which again makes me believe that this may be caused in part by attempting to update the state too frequently.

This is what my code looks like, at the moment. I am very much an amateur, so I would prefer to focus on just solving the specific issue that's bugging me, please don't give me any extensive code reviews, I know it's horrible.

In theory, this video is how it should work, give or take, but to get that I was adding a bit of a delay to every loop, which slows down the process quite a bit. I would like to be able to have it work without the delay, or instead delayed based on the redraw rate of SwiftUI, if that is indeed my issue.

I hope I have included enough detail in this post for someone to give me a helping hand, as I would be very grateful! This isn't any sort of important app, or one to be published, but I would love to be able to at least make my dumb idea do what it is supposed to do.

DispatchQueue.global(qos: .utility).async(execute: babbleQueue!)

You're mutating @State variables on a background queue; this is likely causing races in your code. SwiftUI requires that you only mutate state on the main queue.

In the future, this question is better addressed in Apple's developer forums, because SwiftUI isn't part of the Swift open source project. http://developer.apple.com/forums/

Terms of Service

Privacy Policy

Cookie Policy