A Short Note – iOS Best Practices And Swift Coding Standards With Code Organization, Spacing and Comments

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Code Organization, Spacing and Comments).

In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Code Organization, Spacing and Comments which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.

So Let’s begin.

Code Organization

We can use extensions to organize our code into logical blocks of functionality. Each extension should be set off with a // MARK: – comment to keep things organised.

Protocol Conformance

We can prefer adding a separate extension for the protocol methods when adding protocol conformance to a model. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.

Preferred :

class MyViewController: UIViewController {

  // class stuff here

}

// MARK: - UITableViewDataSource

extension MyViewController: UITableViewDataSource {

  // table view data source methods

}

// MARK: - UIScrollViewDelegate

extension MyViewController: UIScrollViewDelegate {

  // scroll view delegate methods

}

Not Preferred :

class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {

  // all methods

}

Since the compiler does not allow us to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class.

This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the developer.

For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.

Unused Code

Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when our tutorial or book instructs the user to use the commented code.

Aspirational methods not directly associated with the article whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.

Preferred:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

  return Database.contacts.count

}

Not Preferred:

override func didReceiveMemoryWarning() {

  super.didReceiveMemoryWarning()

  // Dispose of any resources that can be recreated.

}

override func numberOfSections(in tableView: UITableView) -> Int {

  // #warning Incomplete implementation, return the number of sections

  return 1

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

  // #warning Incomplete implementation, return the number of rows

  return Database.contacts.count

}

Minimal Imports

Import only the modules a source file requires. For example, don’t import UIKit when importing Foundation will suffice. Likewise, don’t import Foundation if we must import UIKit.

Preferred:

//1
import UIKit

var view: UIView

var deviceModels: [String]

//2
import Foundation

var deviceModels: [String]

Not Preferred:

//1

import UIKit

import Foundation

var view: UIView

var deviceModels: [String]

//2

import UIKit

var deviceModels: [String]

Spacing

Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:

  • Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
  • There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means we should refactor into several methods.
  • There should be no blank lines after an opening brace or before a closing brace.
  • Colons always have no space on the left and one space on the right. Exceptions are the ternary operator ? :, empty dictionary [:] and #selector syntax addTarget(_:action:).
  • Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
  • Avoid trailing whitespaces at the ends of lines.
  • Add a single newline character at the end of each file.

We can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.

Preferred:

//1

if user.isHappy {

  // Do something

} else {

  // Do something else

}

//2

class TestDatabase: Database {

  var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]

}

Not Preferred:

//1

if user.isHappy

{

  // Do something

}

else {

  // Do something else

}

//2

class TestDatabase : Database {

  var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]

}

Comments

When we are needed, we can use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.

We should avoid block comments inline with code, as the code should be as self-documenting as possible.

Exception: This does not apply to those comments used to generate documentation.

We should also avoid the use of C-style comments (/* … */). We can prefer the use of double- or triple-slash.

Conclusion

In this note series, we understood about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. We discussed about iOS Swift based Code Organization, Spacing and Comments concepts which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.

Thanks for reading! I hope you enjoyed and learned about Code Organization, Spacing and Comments concepts in iOS Swift. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow other website and tutorials of iOS as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – iOS Best Practices And Swift Coding Standards With Naming Conventions

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Naming Conventions).

In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Naming Conventions. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.

So Let’s begin.

Overview of Naming Conventions

Descriptive and consistent naming makes code easier to read and understand. We can use the swift naming conventions described in the API Design Guidelines. Some key takeaways include:

  • Striving for clarity at the call site
  • Prioritizing clarity over brevity
  • Using camel case (not snake case)
  • Using uppercase for types (and protocols), lowercase for everything else
  • Including all needed words while omitting needless words
  • Using names based on roles, not types
  • Sometimes compensating for weak type information
  • Striving for fluent usage
  • Beginning factory methods with make
  • Naming methods for their side effects
    • Verb methods follow the -ed, -ing rule for the non-mutating version
    • Noun methods follow the formX rule for the mutating version
    • Boolean types should read like assertions
    • Protocols that describe what something is should read as nouns
    • Protocols that describe a capability should end in -able or -ible
  • Using terms that don’t surprise experts or confuse beginners
  • Generally avoiding abbreviations
  • Using precedent for names
  • Preferring methods and properties to free functions
  • Casing acronyms and initialisms uniformly up or down
  • Giving the same base name to methods that share the same meaning
  • Avoiding overloads on return type
  • Choosing good parameter names that serve as documentation
  • Preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
  • Labeling closure and tuple parameters
  • Taking advantage of default parameters

Prose

When we refer methods in prose, being unambiguous is critical. We can refer method name in the simplest form as possible.

  • Write method name with no parameters. Example: Next, we need to call addTarget.
  • Write method name with argument labels. Example: Next, we need to call addTarget(_:action:).
  • Write the full method name with argument labels and types. Example: Next, we need to call addTarget(_Any?,action:Selector?).

For example using UIGestureRecognizer, Write method name with no parameter is unambiguous and preferred. We can use Xcode’s jump bar to lookup methods with argument labels. We can put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on our clipboard.

Delegates

When we create custom delegate methods, an unnamed first parameter should be the delegated source. UIkit contains numerous examples of custom delegates methods.

Preferred :

func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)

func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool

Not Preferred :

func didSelectName(namePicker: NamePickerViewController, name: String)

func namePickerShouldReload() -> Bool

Use Type Inferred Context

We can use compiler inferred context to write shorter, clear code. 

Preferred:

let selector = #selector(viewDidLoad)

view.backgroundColor = .red

let toView = context.view(forKey: .to)

let view = UIView(frame: .zero)

Not Preferred:

let selector = #selector(ViewController.viewDidLoad)

view.backgroundColor = UIColor.red

let toView = context.view(forKey: UITransitionContextViewKey.to)

let view = UIView(frame: CGRect.zero)

Generics

Generic type parameters should be descriptive, upper camel case names. When a type name doesn’t have a meaningful relationship or role, use a traditional single uppercase letter such as T, U, or V.

Preferred:

struct Stack<Element> { ... }

func write<Target: OutputStream>(to target: inout Target)

func swap<T>(_ a: inout T, _ b: inout T)

Not Preferred :

struct Stack<T> { ... }

func write<target: OutputStream>(to target: inout target)

func swap<Thing>(_ a: inout Thing, _ b: inout Thing)

Class Prefixes

Swift types are automatically namespaced by the module that contains them and we should not add a class prefix such as RW.

If two names from different modules collide, we can disambiguate by prefixing the type name with the module name. However, we can only specify the module name when there is possibility for confusion which should be rare.

import SomeModule

let myClass = MyModule.UsefulClass()

Language

We can use US English spelling to match Apple’s API.

Preferred:

let color = “red”

Not Preferred:

let colour = “red”

Conclusion

In this note series, we understood about iOS Best Practices and Swift Coding Standards With Naming Conventions. We discussed about Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.

Thanks for reading! I hope you enjoyed and learned about Naming Conventions concepts in iOS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow other website and tutorials of iOS as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???


Exit mobile version