6

I'm currently learning ios developement using swift and I was just wondering if there is a way in xcode to

1) set a breakpoint on a variable whenever the value of the variable changes

OR

2) somehow track the change to variable value over time

Thor
  • 9,638
  • 15
  • 62
  • 137
  • I already have several month of learning experience under my belt, just want to take my skills to the next level. but is having trouble debugging one of my beginners app. – Thor Aug 15 '16 at 07:11

2 Answers2

5

Method with Swift didSet and willSet

You can use the print in the console:

class Observable {
    static var someProperty: String? {
        willSet {
            print("Some property will be set.")
        }
        didSet {
            print("Some property has been set.")
        }
    }
}

Method with watchpoints

Watchpoints are a tool you can use to monitor the value of a variable or memory address for changes and trigger a pause in the debugger when changes happen. They can be very helpful in identifying problems with the state of your program that you might not know precisely how to track down.

You can find a great guide here

Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49
  • Thank you so much for helping out! Just out of curiousity, is there a way to observe the value change using xcode debugger? – Thor Aug 15 '16 at 07:17
  • 1
    @TonyStark I updated my post. If it helps you, mark my answer as right, I would appreciate it, thanks :) – Marco Santarossa Aug 15 '16 at 07:21
  • +1 for the link! didn't go through it in great detail yet but it looks really informative, thanks again! – Thor Aug 15 '16 at 07:25
1

I think you should learn about willSet and didSet concepts.

Swift has a simple and classy solution called property observers, and it lets you execute code whenever a property has changed. To make them work, you need to declare your data type explicitly, then use either didSet to execute code when a property has just been set, or willSet to execute code before a property has been set.

Update the value whenever the value was changed. So, change property to this:

 var score: Int = 0 {
  didSet {
      scoreLabel.text = "Score: \(score)"
  }  
}

There is already a good question and answers which expalin this concept.

What is the purpose of willSet and didSet in Swift?

Community
  • 1
  • 1
Mudith Chathuranga Silva
  • 7,253
  • 2
  • 50
  • 58