MJQZ1347 MJQZ1347 - 1 year ago 68
iOS Question

Observing a value of a static var in a class?

I have a class with a static var where the current online connection status is stored. I want to observe the value of

through other classes. I wanted to do this with
, but declaring a
variable as
causes an error:

class ConnectionManager: NSObject {
dynamic static var online = false
// adding 'dynamic' declaration causes error:
// "A declaration cannot be both 'final' and 'dynamic'

What is a most elegant way of doing this?


This my code for the

override func viewDidLoad() {

forKeyPath: "online",
options: NSKeyValueObservingOptions(),
context: nil)

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "online" {
print("online status changed to: \(ConnectionManager.online)")
// doesn't get printed on value changes

Answer Source

As for now, Swift cannot have observable class properties. (In fact, static properties are just global variables with its namespace confined in a class.)

If you want to use KVO, create a shared instance (singleton class) which has online property and add observer to the instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download