iOS Coding Convention

Yuvraj Kale
7 min readJul 27, 2019

Many developers have a question in mind that, how could be my coding convention?

Now the first question comes in mind that, what is coding convention actually?

Coding convention is nothing but a set’s of protocol that is passed by team or by the developer so that whenever it’s time to look into code after a long break or accessing code by a different developer in absence of developer who worked on that code so that he can easily understand the code. Also, it will improve the quality of your code. So now we will directly jump into a self-set protocol.

  1. SWIFT NATIVE TYPES

I suggest you to always use swift native types whenever possible (like Array, Dictionary, Set, String, etc) as every objective c type convert in swift native type automatically.

For example,

BAD HABIT

let statement = NSString(format: “Your name is %@“,name )

Here you are using NSString class which is objective c type so I suggest you to use native type String by using the following correct way of using it.

GOOD HABIT

let statement = “Your name is \(name)”

OR

let statement = “Your name is ” + name

Swift collection types

Do not make NSArray, NSDictionary, and NSSet properties or variables.

BAD HABIT

var arrayOfJSONObjects: NSArray = NSArray()

let names: AnyObject? = arrayOfJSONObjects.value(forKeyPath: “name”)

GOOD HABIT

var arrayOfJSONObjects = [[String: AnyObject]]()

let names: AnyObject? = (arrayOfJSONObjects as NSArray).value(forKeyPath: “name”)

2.Optionals

Swift programming language brings a number of new features that makes developers more easy to write code. like that optional is one of the most simple but effective features in swift that actually saves our app from crashing in absence of any value. But many developers failed to use that feature and invent there own logic to represent no value at all even if swift invent it as optional.

In Swift, an optional type is a type that is used to indicate the potential absence of a value.

Avoid force unwrapping of optionals by using ! Or !! As this will cause your app to crash if the value that you forced unwrapping is nill. So always safely unwrap the variable by using if let, guard let, if let as? guard let as? And optional chaining . Also for downcasting use as?

BAD HABIT of Unwrapping

let google = nill

let url = URL(string:google)!

This will cause app to crash as the google URL is nill

GOOD HABIT of Unwrapping

guard let url = URL(string:google) else{

return

}

OR

if let url = URL(string:google){

……

}

BAD HABIT of downcasting

“as” keyword is used to downcast any type in another type but what if we cast into the different type and if failed to cast it returns nil which causes the app to crash.

let detailController = segue.destination as! detailViewcontroller

this force downrating will cause the app to crash if segue destination is nill

GOOD HABIT of downcasting

guard let detailController = segue.destination as? detailViewcontroller else{

return

}

One more example of using the delegate and calling the delegate method what if the delegate using is nil and you used forced downcasting? It will cause the app to crash.

BAD WAY of optional chaining

delegate!.didselectmethod()

This will crash the app if your delegate is nill

GOOD WAY of optional chaining

delegate?.didselectmethod()

3.If pyramid of DOOM

What is pyramid of DOOM?

In the programming of language pyramid of DOOM is a common problem that arises when a program uses many levels of nested if to control access to a function or variable.

go through the following example,

if let id = jsonObject[“id”] as? Int{

if let name = jsonObject[“name”] as? String{

if let address = jsonObject[“address”] as? String{

}

}

}

Above is the incorrect way to of accessing any function on a certain value.

Correct Way

if

let id = jsonObject[“id”] as? Int,

if let name = jsonObject[“name”] as? String,

if let address = jsonObject[“address”] as? String{

}

Also, make note that always use a new line for next optional to make simple readability

Always put a line break after a guard or if statement so your let statement always at the new line

4.Exceptional Handling

Exception is the event that occurs during the execution of the program, that disrupts a normal program. So, we need to handle such an exception to stop crashing our app.

1. Avoid using forced-try exception try! As this will cause exceptions as if it is nil.

2.Safely handed error by using do statement along with try and catch.

BAD HABIT

let jsonObject = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)

here try! will cause our app to crash if serialization returns nil.

GOOD HABIT

do{

let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)

}catch{

print(error)

}

5.LET vs VAR

let is keyword which is used declare a constant variable which means you are not able to change the value of let variable once it is declared

And where var is exactly opposite to let which is used declare the variable and we can change the value of a variable in the scope of that variable.

1. Whenever possible try to use let instead of var

2. Declare properties of object or trust that is not going to change ever with let

6. Spacing

1. Open curly braces at the same line of statement and close the curly line at the new line

2. Don’t add an empty line after open curly braces or before curly braces.

3. Put else at the same line where if statement end.

4. Put all colons left hugging in except with turnery operator.

Example

BAD HABIT

let testDict = [String : Any]

NOTE: See here the colon is not left aligned it’s in the center

GOOD HABIT

let testDict = [String: Any]

NOTE: See here the colon is left aligned to String

With ternary operators

BAD HABIT

let ternary = (someValue>100) ? “foo” : “bar”

NOTE: See here the colon is not left aligned

GOOD HABIT

let ternary = (someValue>100) ? “foo”: “bar”

NOTE: See here the colon is left aligned which is incorrect

7.Protocol Conformance

In every app, we use protocol and delegate that time we need to confirm the protocol. It will be great if we make separate confirmation for that class.

1.When using the protocol conformance use separate extension for protocol method.

2. Always use // MARK: — SomeDelegate to well organise the code

Example

BAD HABIT

class MyController: UIViewcontroller,UITableviewDelegate,UITableviewDatasource{

//Your code

}

GOOD HABIT

class MyController: UIViewcontroller{

}

extension MyController:UITableviewDelegate{

}

extension MyController:UITableviewDelegate{

}

8.Array & Dictionary

Whenever we are declaring any collection type it’s hard to read all values if the number of values declared is more what if we make it more readable and declare it properly.

BAD HABIT

let array: Array<String>

let dictionary: Dictionary<String,Any>

GOOD HABIT

let array: [String]

let dictionary: [String:Any]

For Array and Dictionary literals, unless literals are very short, splits it into multiple lines. Also opening curly braces on the same line and closing braces at the new line. Put trailing comma for last value or key-value pairs

Example

BAD HABIT

let array = [value1,value2,value3]

OR

let array = [

value1,

value2,

value3

]

Dictionary

let dictionary = [key1: value1,key2: value2,key3: value3]

OR

let dictionary = [

key1: value1,

key2: value2,

key3: value3

]

NOTE: Here there is no trailing comma at the end of the value.

GOOD HABIT

let array = [

value1,

value2,

value3,

]

let dictionary = [

key1: value1,

key2: value2,

key3: value3,

]

NOTE: Here there is trailing comma for last object and every value is at next line.

9. Function Parameter and Function name

If we function name and parameter name are relatable so that new developer can easily understand the why we declare the function.

Example

BAD HABIT

class person{

set(name: String){

//Here this method does not clear what it is used to

}

setSomething(firstName: String, lastName: String){

//Here this method does not match with parameter what we are going to set

}

}

GOOD HABIT

class person{

setName(name: String){

//Here we are clear that this method is used to set name

}

setName(firstName: String, lastName: String){

//Here this method is used to set name also which clear.

}

}

10.Constants

Whenever we are declaring cosntant and every time the program runs it will assigned new memmory even if it is already present in the memmory.

Following is the rules to keep in mind before declaring any variable.

1. Use Static let to declare constants.

2. Prefer declaring constants in the scope where it is useful instead of declaring over a shared file

3. Use a group of constants over enum for identical constants

Example

enum SegueIdentifier {

Static let login = “LoginSegue”

Static let signUp = “SignUpSegue”

}

enum StoryBoardIdentifier {

Static let Main = “main”

Static let Launchscreen = “Laucnhscreen”

}

11.Naming Convention

The naming convention is an important part of programming language. Which helps us to understand the behavior/type of function/variable.

1. Always use camelCase notation for the parameter. camelCase notation is capitalising first character of each word except first word.

Example

func ToInt(String: valueToConvert)

2. Always use PascalCasing for the all public member, methods,Identifier,object.Pascal casing is capitalising first character of each word.

Example

func ToInt(String: valueToConvert)

3. Always Define Constant with all characters in word in capital.

4. Never use the underscore for any variable declaration or method or parameter declaration.

Class and Structure

1. name classes and structs with nouns or noun phrases, using PascalCasing.

2. ending the name of derived classes with the name of the base class.

Example

1. If class is derriving from ViewController i.e if base class is Viewcontroller then the deprived class name should be like TestViewcontroller

2. Another example if class is derrived from Exception then class name should be like ArgumentOutOfRangeException.

Always use any variable name ending with its base class

Example:

loginLable , loginButton, moveDragGesture etc.

12.Button Action and Outlet

Action Name

Action name should always start with onClick

If you are using login button then the button action should be like onClickLogin

OutletName

If you are using the login button the button name should like loginButton

This is how you have to give name for any Action and the outlet.

For example

Lable — loginLable

textField — loginTextField

Overview of this is you have to give singular type name followed by the base class

like textField, lable, button etc.

13. Bundle ID

Bundle id name should be like com.company.appname. It is better to use every letter should be small.

--

--