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
.