Change an Int variable value in LLDB

Viewed 466

Environment: Xcode 11.3.1/Swift 5

Here is the function:

func lldbTest() {
    var switchInt = 1

    ...// do something and set a break point here

    if switchInt == 1 {
        print("switchInt == 1")
    } else if switchInt == 2 {
        print("switchInt == 2")
    }
}

I debug before enter the if statement, and I change switchInt to 2 in lldb

e switchInt = 2
p switchInt
(Int) $R4 = 2

but it still print "switchInt == 1" result

2 Answers

I guess the behavior is because the compiler has already evaluated the if statement "if switchInt == 1" because there's no code that changes the value of switchInt before that line. I tried the below and was able to get the behavior desired.

var switchInt = 1

for i in 0..<10 {
    switchInt = 0
}

if switchInt == 1 {  -> Put a break point here and use (lldb) e switchInt=2
    print("switchInt == 1")
} else if switchInt == 2 {
    print("switchInt == 2")
}

Now execute the command p switchInt and it will have the value 2. Step through the breakpoint and it will print switchInt == 2.

Setting variables from the debugger in Swift is somewhat hit and miss. Because swift uses so many wrapped objects (Int's for instance are actually a "struct"), the compiler has to do a fair amount of optimization even at -Onone or the code will run unacceptably slowly.

The debugger is often told only about a shadow copy of the variable, and not the location that is actually being used in code. You can try various tricks like Felix suggests, but at present you're not guaranteed to succeed...

This is a known bug, but for technical reasons is one that is tricky to solve.

Related