With the new Xcode 14, the biggest feature πŸ˜‚ of Swift 5.7 has to be the enhancement of the unwrapping syntax. We can delete a lot of code with a simple find & replace.

  • Replace > Regular Expression > (if|guard)(\s+)(let|var) (\w*) = \4([\s,])(?!as)
  • With $1$2$3 $4$5
  • Tada!

It’s that simple to remove lots of unnecessary code.

The regex is mostly copied from this tweet, with added support for multi-line guard-let statements.

Regex replacement is useful

The same trick can be used for any repetitive refactoring. So if you are not sure how the regex works, this is a quick explanation:

  • (if|guard) – Rounded brackets are capture group, and in this case it ca be β€œif” or β€œguard”
  • (\s+) – Capture 1 or more whitespaces, including line breaks
  • (\w*) – Capture any word
  • \4 – The 4th capture group, which is the any word above
  • [\s,] – Square brackets are character set, and in this case it is any whitespaces or ,
  • (?!as) – The prefix ?!is a negative lookahead, which means the regex will only match if it does NOT have β€œas”. This is to prevent matching eg. if let foo = foo as? Bar

No code is best code.

UPDATED: Improving for other cases

The above regex does not fix all unwrapping. One shortcoming is that it replaces only the first in a if-statement. To replace the 2nd and subsequent unwrapping, you can run another regex.

  • Replace (let|var) (\w*) = \2([\s,])(?!as|\?)
  • With $1 $2$3

You might have compiler warning as this regex matches more loosely. I have also added another negative lookahead for β€œ?”, to prevent matching statements like let foo = foo ?? 42.




Back to Home