I'm trying to create an async subclass of Operation. The code crashes on the getter of the "state" Property. I have found an article which solves the async Subclass, but i'm curios as to why a crash happens at queue.sync { self._state } The willSet and DidSet of the _state property is called and the control moves to the getter state where it crashes image of the crash
class ConcurrentOperation: Operation {
private enum State: String {
case ready = "isReady"
case executing = "isExecuting"
case finished = "isFinished"
}
private var _state: State = .ready {
willSet {
willChangeValue(forKey: newValue.rawValue)
willChangeValue(forKey: _state.rawValue)
}
didSet {
didChangeValue(forKey: _state.rawValue)
didChangeValue(forKey: oldValue.rawValue)
}
}
private let queue = DispatchQueue(label: "com.concurrentOperation.chanakkya", attributes: .concurrent)
private var state: State {
get {
queue.sync { self._state }
}
set {
queue.sync(flags: .barrier) {
self._state = newValue
}
}
}
override var isReady: Bool {
super.isReady && state == .ready
}
override var isExecuting: Bool {
state == .executing
}
override var isFinished: Bool {
state == .finished
}
override func start() {
guard !isCancelled else {
finish()
return
}
if !isExecuting {
state = .executing
}
main()
}
override func main() {
fatalError()
}
func finish() {
if isExecuting {
state = .finished
}
}
override func cancel() {
super.cancel()
finish()
}
}

You have to use a temp variable