Why can't I change the value of a global variable in WatchKit - swift?

I am making a simple WatchKit app. I have a golbal int variable with a value of 0 in the first interface of ControlController.

Here is my first interface:

import WatchKit
import Foundation
import UIKit

var index:Int = 0

class InterfaceController: WKInterfaceController {

    .....
}

      

in the secondView interface, I want to change the value of this global variable:

import UIKit
import WatchKit

class secondInterfaceController: WKInterfaceController {


    override init(context: AnyObject?) {
        // Initialize variables here.
        super.init(context: context)

        // Configure interface objects here.
        NSLog("%@ init", self)

        println("index: \(index)")

        index = 2


    }


}

      

But I got the error "Cannot assign the result of this expression" for the variable index. I don't know why, and I want to know how to do it. I can change the value of a global variable for an IOS app. Thanks to

+3


source to share


2 answers


I found a solution. If you want to use a global variable inside interfaces, you must set all these interfaces to the same "target membership"



0


source


I reproduced your code to test the problem, intending to test potential solutions. Instead, I confirmed that this question is not reproducible.

To be able to run the code, I had to change it to override func awakeWithContext(context: AnyObject?)

. From the Beta and Beta Release Notes released today:

WKInterfaceController initWithContext: deprecated. Use awakeWithContext: instead. The designated initializer for WKInterfaceController is now init.

Considering what your code is using init(context: AnyObject?)

and you are not getting this error message:



The initializer does not override the designated initializer from its superclass

... this indicates that you are using Xcode 6.2 before beta 3. So it is possible that there was an early beta that caused your problem. Upgrading to a beta version to date and retesting this issue would be highly beneficial.


There are many programmers in the linked note who argue that using globals is highly undesirable and that using a different approach, even singleton, is preferred. I'll just bring this to your attention for a peek if you haven't formed an opinion on this debate yet.

+2


source







All Articles