Skip to content

Instantly share code, notes, and snippets.

@pruinis
Forked from calebd/AsynchronousOperation.swift
Created October 15, 2016 20:22
Show Gist options
  • Save pruinis/13be23760eed698b82c34728035e533b to your computer and use it in GitHub Desktop.
Save pruinis/13be23760eed698b82c34728035e533b to your computer and use it in GitHub Desktop.
Concurrent NSOperation in Swift
//
// ConcurrentOperation.swift
//
// Created by Caleb Davenport on 7/7/14.
//
// Learn more at http://blog.calebd.me/swift-concurrent-operations
//
import Foundation
class ConcurrentOperation: NSOperation {
// MARK: - Types
enum State {
case Ready, Executing, Finished
func keyPath() -> String {
switch self {
case Ready:
return "isReady"
case Executing:
return "isExecuting"
case Finished:
return "isFinished"
}
}
}
// MARK: - Properties
var state = State.Ready {
willSet {
willChangeValueForKey(newValue.keyPath())
willChangeValueForKey(state.keyPath())
}
didSet {
didChangeValueForKey(oldValue.keyPath())
didChangeValueForKey(state.keyPath())
}
}
// MARK: - NSOperation
override var ready: Bool {
return super.ready && state == .Ready
}
override var executing: Bool {
return state == .Executing
}
override var finished: Bool {
return state == .Finished
}
override var asynchronous: Bool {
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment