DEV Community

loading...

Swift Minimal Coding Rules

noahkuwae profile image noah.k ・2 min read

For whom is this?

  • Entry level developers (or who works with them)
  • Wants to code quickly but keep the minimum code quality
  • Already introduced SwiftFormat and SwiftLint

You can find various coding rules, but many of them are long and might be overwhelming. This rule is simple enought to quickly start, easy to understand even for beginners.

Rules

Use Understandable Names

Naming is one of the most important points in code.
Take your time to think of naming.

Segregate Classes from View Controllers

Don't put code unrelated to view into view controllers.
Don't put code unrelated to app status into AppDelegate.
Conform to Single Responsibility Principle.

Separate Storyboards and View Controllers

In team development, you should avoid conflict.

Put Common Code into Protocols

Don't Repeat Yourself.
Adopt Protocol Oriented Programming.
https://dev.to/noahkuwae/protocol-oriented-programming-pop-brief-summary-4i5b

Put Common UI Parts into Xibs

Again, Don't Repeat Yourself.

Conform to Cocoa MVC

This should be determined in each team, but MVC is basic and the most understandble architecture.

Separate Classes (or Structs) by Extensions for each Protocol

This increases readability of the code.

Before:

class SampleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { ... }
...
}

After:

class SampleViewController: UIViewController { ... }

extension SampleViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
}

extension SampleViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { ... }
}

Handle Errors

If you don't handle them now, add some comment like // TODO.

Use assert or fatalError for Unexpected Cases

If you merely use return, you'll have difficulty in fixing it later.

Split Your Code into Methods

If you want to write a comment for a chunk of code, it's a sign for creating a method.

Reference

15 Rules for Writing Quality Code | | InformIT

Note

This is subject to change, because currently I'm running a project using this rule (in 2019).
Some update might occur during the project.

Discussion (0)

pic
Editor guide