iOS Best Practices. Part 2: Swift Code Style

Maksim Vialykh
3 min readNov 15, 2017

--

As a continuation of Part 1: Objective-C Code Style

swift code style

Correctly chosen spacing is what helps to organize your code.

spacing

No comments… Write clear code following S.O.L.I.D principles.

Use Type Inferred Context — swift powerful feature.

comments, delegates, type inferred context

Protocols should be implemented in separate extensions.

Class should include only the code that describes inner functionality.

protocol conformance

Don’t collect unused code. You can always restore this code from version control system.

unused code, minimal imports

Classes vs Structures. It’s your choice…
So, i guess we should prefer structures to classes. This path provides benefits with memory management.
Of course, we have lots cases where we must use classes.

Use syntactic sugar in computed properties.

classes vs structures

Don’t forget about final.

final, function declaration, closure expressions

Collect global values in separated Constants file.
*You can use structures with private init() as an alternative of enum.

Optimize conditions for optional unwrap, write all arguments sequentially in one condition.

constants, optionals

Use lazy initialization to optimize memory management.

Again about Type Inference & Syntactic Sugar.

lazy initialization, type inference, syntactic sugar

Think more about memory management.
Extend object lifetime in code block with [weak self], guard let `self` = self else { return } constructions.

memory management, object lifetime

Write conditions with “Golden Path”.
Use guard to unwrap multiple optionals.

golden/happy path, guard

Did you come from Objective-C world?
- Yes!
Stop using semicolons!

semicolons, parentheses

This was a small guide about swift code style.

iOS Best Practices to be continued…

Part 3: Architecture

--

--