Skip to content

Instantly share code, notes, and snippets.

@kingiol
Forked from Sorix/AsynchronousOperation.swift
Created November 18, 2018 08:26
Show Gist options
  • Save kingiol/a21b7dfd3edff6b09d2f37da627488b0 to your computer and use it in GitHub Desktop.
Save kingiol/a21b7dfd3edff6b09d2f37da627488b0 to your computer and use it in GitHub Desktop.
Subclass of NSOperation to make it asynchronous in Swift 3
//
// AsynchronousOperation.swift
//
// Created by Vasily Ulianov on 09.02.17.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
/// Subclass of `Operation` that add support of asynchronous operations.
/// ## How to use:
/// 1. Call `super.main()` when override `main` method, call `super.start()` when override `start` method.
/// 2. When operation is finished or cancelled set `self.state = .finished`
class AsynchronousOperation: Operation {
override var isAsynchronous: Bool { return true }
override var isExecuting: Bool { return state == .executing }
override var isFinished: Bool { return state == .finished }
var state = State.ready {
willSet {
willChangeValue(forKey: state.keyPath)
willChangeValue(forKey: newValue.keyPath)
}
didSet {
didChangeValue(forKey: state.keyPath)
didChangeValue(forKey: oldValue.keyPath)
}
}
enum State: String {
case ready = "Ready"
case executing = "Executing"
case finished = "Finished"
fileprivate var keyPath: String { return "is" + self.rawValue }
}
override func start() {
if self.isCancelled {
state = .finished
} else {
state = .ready
main()
}
}
override func main() {
if self.isCancelled {
state = .finished
} else {
state = .executing
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment