Cactus can help your business benefit from AI through "StartAI", the AI program of Agoria and Vlaio

iOS Best Practices. Part 2: Swift Code Style

The previous articlePart 1: Objective-C Code Style 

In this article you will learn how to write code for mobile apps in Swift language.

About US: Since 2007, CactusSoft has developed hundreds of mobile applications. We offer full-cycle mobile software engineering that also incorporates server-side implementation. With our solid expertise in Android, iOS, Windows Phone and HTML5 we deliver superior quality native mobile apps and cross-platform solutions.

Correctly chosen spacing is what helps to organize your code.

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

Use Type Inferred Context — a powerful Swift feature.

Protocols should be implemented in separate extensions.

Class should include only the code that describes inner functionality.

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

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

Use syntactic sugar in computed properties.

Don’t forget about final.

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

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

Use lazy initialization to optimize memory management.

Again, consider 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.

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

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

This was a brief guide to the Swift code style.

Continue readingiOS Best Practices. Part 3: Architecture > > >


vialyx

Maxim Vialykh is iOS Tech Lead.

Technical Background
Programming languages: Swift, Objective-C, Java
Technologies and Platforms: iOS, Android, Windows Phone, Amazon S3, Google Cloud, Google APIs, Facebook APIs
Frameworks: PhoneGap, Xamarin
Tools: Invision, SVN, Git, PhoneGap, Titanium, Xamarin, Sketch, xCode, IntelliJ IDEA

Share this page
We are experts
If there is a project needing help or even a skill set you are missing, contact us.

Similar Articles

Contact us today to explore how Cactus
can support your digital journey
Subscribe To Our Newsletter
To get new inspiring articles and news right in your inbox.