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)
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.