Five Effective Commenting Practices for Swift-iOS
We all can write comments, but do we know when and how to write comments on our code to make it more impactful?
It's essential to use comments in code to document our thought process and make it easier for others to understand our code. But comments will be more impactful when we maintain best practices (including when and what to write comments). This blog will discuss best comment practices when working with SwiftUI on iOS application development.
If you are having difficulty understanding the comment examples in this blog post, don't worry. The primary focus of this blog is to understand the purpose of commenting. It is important for every good programmer to have a strong sense of when and how to comment on their code, and this blog aims to help you build that skill.
Jokes apart, let's discuss the Five Effective "when and how":
1. Explain the purpose of a function or method
When writing a function or method, it's important to explain its purpose in a comment clearly. This will help other developers understand the purpose of the function and how it fits into the overall application.
For example:
// Returns current date in 'dd/mm/yyyy' format
func getCurrentDate() -> String {
// code to get current date
}
2. Explain complex code
If we have written a complex piece of code that may be difficult for others to understand, it's helpful to include comments explaining the logic behind it. This will make it easier for others to follow our thought process and understand how the code functions.
Here is an example of a complex piece of code in Swift with comments explaining the logic behind it:
func findLargestNumber(in array: [Int]) -> Int {
// Initialize variables to track current largest number & index
var largest = array[0]
var largestIndex = 0
// Iterate through array and update largest number and its index
for (index, element) in array.enumerated() {
if element > largest {
largest = element
largestIndex = index
}
}
// Return the largest number
return largest
}
In this example, the findLargestNumber(in:)
function takes an array of integers as input and returns the largest number in the array. The comments above each block of code explain the purpose of the variables and the logic behind the for loop that iterates through the array and updates the largest number and its index. This will help other developers understand the code and follow the thought process behind it.
3. Comments to document changes
If we make changes to our code, it's essential to document those changes in comments. This will help other developers understand the reasoning behind the changes and how they may impact the overall application.
Here is an example of using comments to document changes in Swift code:
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Added setup code for new feature
setUpNewFeature()
}
// MARK: - New Feature
func setUpNewFeature() {
// Initialize and configure new feature
let newFeature = NewFeature()
newFeature.configure()
}
// MARK: - Changes Made
// - Added setUpNewFeature() to initialize and configure new feature
// - Added newFeature property to store the instance of new feature
// - Modified viewDidLoad() to call setUpNewFeature()
In this example, we have added a new feature to our view controller and made some changes to the viewDidLoad()
method to initialize and configure the new feature. We have also added a property to store the instance of the new feature. To document these changes, we have added a comment at the top of the block of code outlining the changes that were made, including the addition of the new function and the modifications to viewDidLoad()
.
4. Keep comments concise and relevant
While it's important to include comments in our code, it's also important to keep them concise and relevant. Avoid writing long, unnecessary comments, as they can clutter our code and make it harder to read.
Here is an example of concise and relevant comments in Swift code:
// Calculate the distance between two points
func distance(x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
let dx = x2 - x1
let dy = y2 - y1
return sqrt(dx*dx + dy*dy)
}
// Check if a point is within a circle
func isInsideCircle(x: Double, y: Double, centerX: Double, centerY: Double, radius: Double) -> Bool {
// Calculate the distance between the point and the center of the circle
let distance = self.distance(x1: x, y1: y, x2: centerX, y2: centerY)
// Return true if the distance is less than the radius, false otherwise
return distance < radius
}
In this example, we have defined two functions: distance()
and isInsideCircle()
. Both functions have concise and relevant comments that explain their purpose and how they work. The comment for distance()
explains that it calculates the distance between two points, while the comment for isInsideCircle()
explains that it checks if a point is within a circle by calculating the distance between the point and the center of the circle and comparing it to the radius of the circle. These comments help clarify the code's purpose and function, making it easier for other developers to understand and maintain.
5. Use comments to improve readability
In addition to explaining the purpose of our code, comments can also be used to enhance the readability of our code. For example, we can use comments to separate code sections or highlight important points.
Here is an example of using comments to improve readability in Swift code:
// MARK: - Data Loading
// Load data from the API
func loadData() {
// Make API call
API.loadData { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let data):
// Process and save the data
self.processAndSaveData(data)
case .failure(let error):
// Handle the error
self.handleError(error)
}
}
}
// Process and save the data
func processAndSaveData(_ data: Data) {
// Convert the data to a model object
let model = try? JSONDecoder().decode(Model.self, from: data)
// Save the model object to Core Data
try? CoreDataManager.shared.save(model)
}
// Handle the error
func handleError(_ error: Error) {
// Log the error
print("Error: \(error)")
}
In this example, we have a class with three functions: loadData()
, processAndSaveData()
, and handleError()
. To improve the readability of the code, we have added comments to separate the different sections and to explain the purpose of each function. The MARK
comment at the top of the block of code separates the Data Loading
section from the rest of the code, while the comments above each function explain what the function does. These comments help to break up the code and make it easier to understand and follow.
Last Words
In conclusion, following best comment practices when working with Swift on iOS application development is crucial for maintaining clean, well-documented code. By explaining the purpose of our code, documenting changes, and keeping comments concise and relevant, we can make it easier for us and others to understand and work with our code.
For any queries or suggestions, connect with me here.