Erik Erik - 1 year ago 107
iOS Question

NSOperation property overrides (isExecuting / isFinished)

I am subclassing

in Swift and need to override the
properties since I am overriding the

The problem I run into is how to preserve key-value observing (KVO) while also being able to override these properties.

Normally in Obj-C this would be rather easy to redeclare the properties as
in the class extension
JSONOperation ()
definition. However, I don't see this same capability in Swift.


class JSONOperation : NSOperation, NSURLConnectionDelegate
var executing : Bool
get { return super.executing }
set { super.executing } // ERROR: readonly in the superclass

// Starts the asynchronous NSURLConnection on the main thread
override func start()
self.executing = true

self.connection = NSURLConnection(request: self.request, delegate: self, startImmediately: true)

So here is the solution I have come up with, but it feels awfully ugly and hacky:

var state = Operation()

struct Operation
var executing = false
var finished = false

override var executing : Bool
get { return state.executing }
set { state.executing = newValue }

override var finished : Bool
get { return state.finished }
set { state.finished = newValue }

Please tell me there is a better way. I know I could make a
var isExecuting
instead of the whole
, but then I have two similarly named properties which introduces ambiguity and also makes it publicly writable (which I do not want).

Oh what I would do for some access modifier keywords...

Answer Source

From the swift book:

You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override.

I think you'll find that this works:

override var executing : Bool {
    get { return _executing }
    set { 
        _executing = newValue 
private var _executing : Bool
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download