Swift Smells

Identifying Areas for Refactoring in Swift

Russell Stephens
Compass True North
2 min readAug 24, 2017

--

Code smells are areas of code, that in spite of being both semantically and syntactically correct, could potentially lead to deeper issues. A slippery slope, if you will:

A code smell is a surface indication that usually corresponds to a deeper problem in the system — Martin Fowler

When left unchecked, these bits of code, can begin to slow down project velocity due to duplicate code or through accumulation of technical debt, and add additional complexity via additional code paths to handle incremental product enhancements during the project lifecycle.

The ways to combat these kinds of smelly smells are outlined in Refactoring and Clean Code. Two books which I believe will make any developer that much better.

However, as programming languages and coding styles evolve and change due to the rise of more functional programming languages such as Swift and Kotlin, there are additional methods that can be added to your toolkit.

Lets explore some ways to identify and fix common smells in swift.

Replace func with var for computed properties

When a func returns a value or property

Use var to increase inline readability

Pull Up Loop Condition

If you are using a conditional in a loop to filter

Use .filter

Use Map to Append

When using a for loop to append

Use .map instead

Use Reduce to Total

When using a for loop to compute a total

use .reduce

The onus is on us to keep our code clean and smell free. Using spare cycles and downtime to tackle smells and technical debt and is a great way to pay it forward for your team and organization.

If you have found additional patterns that work for you, let us know in the comments below!

--

--