-2

In a file called Menu, I have this:

class Menu: UIViewController {
var no_of_swipes = 99

@IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
}
}

And in another file I have this: class Game: UIView {

func didMoveToView(view: UIView) {
    /* Setup your scene here */

    var swipes = Menu()

    var no_of_swipes: Int = 0 {
        didSet {
            println("\(swipes.no_of_swipes) should be three")
        }
    }
}

However when I press the button in Menu, triggering a segue that moves to the second file. The console states that no_of_swipes = 0. In // line x, if I remove = 0, I receive an error about having an initialiser. So, my question is: why isn't no_of_swipes 3? I think this is a problem either with obtaining no_of_swipes or with the observer.

Thank you in advance

William Clark
  • 91
  • 1
  • 3
  • 11

1 Answers1

3

Your problem is that you misunderstood the rationale for didSet. This is performed when you assign something to a property. Paste the following in Playground.

class Menu {
  var no_of_swipes = 5

  @IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
  }

}

var swipes = Menu()
var no_of_swipes: Int = 0 { //line x
didSet {
  println("i have been changed, and \(swipes.no_of_swipes) is what we do not get")
}
}

no_of_swipes = 99
println(no_of_swipes)
no_of_swipes = swipes.no_of_swipes
println(no_of_swipes)

I hope it's self explanatory.

To amend according to the comments:

class Menu {
  var no_of_swipes = 5
  var subscriber:((Int)->())?

  @IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
    subscriber?(no_of_swipes) // for convenience pass the number
  }

}

class MyOtherClass {
  var swipes = Menu()
  init() {
      swipes.subscriber = myActionOnSwipe
  }

  func myActionOnSwipe(swipes:Int) {
    println("Swipes is \(swipes)")
  }
}

If you add the following (also in Playground):

let c1 = MyOtherClass()
c1.swipes.pressedThreeSwipes(c1)

you will see how it works.

qwerty_so
  • 35,448
  • 8
  • 62
  • 86