CoreStore transaction.edit suggesting comments using the same variable name protects us from misusing the non-transaction instance

28 Views Asked by At

From the document I found this code:

let jane: MyPersonEntity = // ...

CoreStore.perform(
    asynchronous: { (transaction) -> Void in
        // WRONG: jane.age = jane.age + 1
        // RIGHT:
        let jane = transaction.edit(jane)! // using the same variable name protects us from misusing the non-transaction instance
        jane.age = jane.age + 1
    },
    completion: { _ in }
)

Not sure why we need to do this // using the same variable name protects us from misusing the non-transaction instance

As swift suggest me to use two of them:

enter image description here

1

There are 1 best solutions below

0
MartinM On BEST ANSWER

That suggestion makes use of the variable name shadowing feature that swift has.

Xcode autocomplete will still show you both "jane", as the other one with the name name also is in the same scope, although can never be used - as it is shadowed. It does not matter what you select there. Because of that reason it is the safest way to handle transaction objects because it prevents you from accidentially using the wrong one.