I started using
Swift in
my projects in 2015 and, as any Swift newbie, I was surprised by the lack of code style guidelines. Here I will share my experience of 3 years and point guidelines that worth following in different aspects of development.
Apple Swift API Design Guidelines provide great rules for
naming. I also recommend to use Objective-C style prefixes for public
extensions to avoid possible conflicts:
/// MARK: Module XXX
extension UIImageView {
func xxx_loadImageFromURL(_ url: URL) {
// ...
}
}
// ...
customImageView.xxx_loadImageFromURL(url)
Built-in Xcode formatter (
^I
) closes most questions with
indentation. Just accept, that sometimes it can produce strange results, like this:
URLSession.shared.dataTask(with: apiURL) { (data, _, err) in
}.resume()
instead of this:
URLSession.shared.dataTask(with: apiURL) { (data, _, err) in
}.resume()
Considering newlines, I recommend to follow good old
Google Objective-C Style Guide, which is stating:
"Use vertical whitespace sparingly."
All the rest is covered by
The Official raywenderlich.com Guide. This guide is consistent and detailed, yet simple. It's widely adopted in different projects and tutorials, so it's well tested and recognizable. Note, that the guide is optimized for tutorials and sample code, which is good, because it's easy to read. But you can ignore some rules, like Minimal Imports or Use Type Inferred Context, because they don't improve reading but can slow down the writer.
While writing this post I found another style guide from
LinkedIn. I don't recommend to follow it. Some rules listed there are obvious, some duplicate Xcode warnings, and some rules are disputable. The guide is way too strict, too large to remember, and thus it will be hard to adopt in your team.