skip to Main Content

I am trying to change a let value while I am in mid-debug on Xcode (Xcode 12). But, when I try this debugger command

expression isLongBoxRide = true

I get this error in the Xcode debugger terminal. "error: cannot assign to value: ‘isLongBoxRide’ is immutable isLongBoxRide = true" It won’t let me change a let value while debugging. It works when I try to change a var. I am just curious if it is even possible to change a let value while debugging on Xcode. It would be really nice if that was possible.

3

Answers


  1. As far as I know Let can not be changed, that the all purpose of let.
    You are Letting it have a constant value
    if you want to change, use var to be a variable

    Login or Signup to reply.
  2. The problem is that the compiler might analyze the let constant at compile time and then optimize your code. For example, think of something like:

    func x() -> String {
        let doit = false
        if (doit) {
            return "Yes"
        } else {
            return "No"
        }
    }
    // ...
    let result = x()
    

    A clever compiler will change this to

    func x() -> String {
        return "Yes"
    }
    // ...
    let result = x()
    

    or even throw away the call of x() completely:

        let result = "Yes"
    

    Hence, there is no doit constant at all, expecially there is no return "No" branch in your program any more.
    This is an extreme example, and the compiler typically will do so only in release mode, but you can see that it’s not easy to allow constants to be changed during debugging, because the compiler might have to revert some opimizations.

    Login or Signup to reply.
  3. AFAIK let and var are not just cosmetics for your code. It has involvement in physical memory management. The let constant are store in the heap, while var are in the stacks. It affects the access time. So you basically cannot change a let variable without breaking the memory stack.

    What you can try is to use a var for DEBUG compilation and let for RELEASE with something like :

    #if DEBUG
    var foo: Bar
    #else
    let foo: Bar
    #endif
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search