Nico
Nico

Reputation: 6359

How to trigger a break when an Array is empty?

In my app, I have a problème when I try to reach an index in an Array, the Array is actually empty. I cannot find what is emptying it so I was wondering if it's possible with the debugger to create a dynamic breakpoint that will pop up when my array is empty. So as soon as something is either resetting the array or taking away its last object, I'd like to know.

I tried to create a symbolic breakpoint with "myArray.isEmpty == true" as the condition but it doesn't look to work the way I want.

Is it possible or I'm just dreaming?

Thanks

Upvotes: 1

Views: 228

Answers (3)

Airspeed Velocity
Airspeed Velocity

Reputation: 40963

As @kendall mentions, you could use didSet to detect when the array is being emptied, and put a breakpoint on it:

// a acts like a normal variable
var a: [Int] = [] {
    // but whenever it’s updated, the following runs:
    didSet {
        if a.isEmpty {
            // put a breakpoint on the next line:
            println("Array is empty")
        }
    }
}

a.append(1)
a.append(2)
println(a.removeLast())
// will print “Array is empty” before the value is printed:
println(a.removeLast())  

Upvotes: 1

What you want is called a Watchpoint, which lets you monitor changes in memory. I'm not sure yet how to set one on a Swift Array, but that could be a good starting point for research.

One idea would be to add a didSet{} block to the property that holds the array, adding a log statement within - break on that based on your condition that the array is empty.

Upvotes: 1

ColinE
ColinE

Reputation: 70162

To the best of my knowledge this isn't possible with Swift and Xcode (or with any other language of IDE I have used). To make this work the IDE would have to continually evaluate the given expression at every step of programs execution.

Now, if arrays were classes, you could subclass and add a breakpoint in an override isEmpty method, but as they are classed you cannot. :-(

Upvotes: 0

Related Questions