3

I'm reading from Erica Sadun's Swift Style book and playing around with some code.

She suggests:

Prefer using same-name shadowing in conditional bind. “This approach is both conventional and safe:

guard​ ​let​ x = x { ... } ​// yes​

guard​ ​let​ y = x { ... } ​// no​

Deliberate same-name shadowing ensures the the unwrapped value’s role follows the logical intent established by the name prior to the if or guard statement. Introducing a new name blurs the line of those semantics and can prove dangerous. Consistent same-named shadowing prevents you from adding an unintentional shadow to symbols in the parent scope.

Regardless of this being a good opinion or not:

In my code, I'm trying to do:

guard let data = data else{...}

but I get the following error:

Definition conflicts with previous value

A simplified version of my function is:

func process(){
  data : AnyObject?

  if x == nil{ data = m}
  else if x > 5{ data = j}
  guard let data = data else { return } // Definition conflicts with previous value
  somefunc(data)
}

If I place the guard statement inside the if or else if then the error would go away. But that's not what I want.

Is there any workaround to still be able to do same-name shadow.

EDIT: I tried using backticks and I get the following errors: enter image description here

  • Expected Pattern
  • Braced block of statements is an unused closure
mfaani
  • 33,269
  • 19
  • 164
  • 293

0 Answers0