The previous article: Part 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.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-1.jpg)
No comments… Write clear code following S.O.L.I.D. principles.
Use Type Inferred Context — a powerful Swift feature.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-2.jpg)
Protocols should be implemented in separate extensions.
Class should include only the code that describes inner functionality.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-3.jpg)
Don’t collect unused code. You can always restore this code using the version control system.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-4.jpg)
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.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-5.jpg)
Don’t forget about final.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-6.jpg)
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.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-7.jpg)
Use lazy initialization to optimize memory management.
Again, consider Type Inference & Syntactic Sugar.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-8.jpg)
Think more about memory management.
Extend object lifetime in code block with [weak self], guard let “self” = self else { return } constructions.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-9.jpg)
Write conditions with “Golden Path”.
Use guard to unwrap multiple optionals.
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-10.jpg)
Did you come from Objective-C world?
– Yes!
Stop using semicolons!
![](https://cactus-now.com/wp-content/uploads/2019/10/swift-11.jpg)
This was a brief guide to the Swift code style.
Continue reading: iOS Best Practices. Part 3: Architecture > > >
![vialyx](https://cactus-now.com/wp-content/uploads/2018/01/Cactus2600-1.jpg)
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