Please do this in your Swift Code
If your MR is often rejected when code reviews maybe you do the same thing as I did, these are some mistakes that have happened to me when requesting MR some because it’s not clean code.
Choose the right looping
Sometimes in the swift code you often make mistakes in choosing which code is right, one of which is like choosing “loop array”
//Before
response["data"].forEach { (_, json) in
for (key, item) in result.enumerated() {
if item.1["id"].stringValue == json["id"].stringValue {
dataA[key].status = json["data"]["status"].boolValue
}
}
}
// After
response["data"].arrayValue.forEach { (json) in
for index in 0..<(self?.dataB.count ?? 0) {
if self?.dataB[index].symbol == json["id"].stringValue {
self?.dataB[index].status = json["data"]["status"].boolValue
}
}
}
Map or reduce in code
When i’ll make the code always use “for loop” on data, rarely use map() or reduce(). this time I will add a map() or reduce() to reduce the line code. This example for make clean code use “.map”.
//Map()
//Before
response["data"].forEach { (_, json) in
for (key, item) in result.enumerated() {
if item.1["id"].stringValue == json["id"].stringValue {
dataA[key].status = json["data"]["status"].boolValue
}
}
}
// After
let sortedArray = students.sorted(by: { $0.score > $1.score })
Reduce Similar Code
Wrong when create function similar or duplicate code that exist for that, this is a way to make your code cleaner. create a new file for handle same function.
//Before
Class ViewControllerA: UIIVewController {
.
.
.
func handleA(value: status) {
if value == .success {
print("success")
print("prosess")
} else {
print("failed")
}
}
}
Class ViewControllerB: UIIVewController {
.
.
.
func handleB(value: status) {
if value == .success {
print("success")
print("prosess")
} else {
print("failed")
}
}
}
// After
class HelperManager{
static let sharedInstance = HelperManager()
func requestForLocation(value: status){
if value == .success {
print("success")
print("prosess")
} else {
print("failed")
}
}
}
Class ViewControllerA: UIIVewController {
override func viewDidLoad() {
super.viewDidLoad()
HelperManager.sharedInstance.requestForLocation(value: .success)
}
}
Class ViewControllerB: UIIVewController {
override func viewDidLoad() {
super.viewDidLoad()
HelperManager.sharedInstance.requestForLocation(value: .failed)
}
}
When to Use “self” in a method?
Don’t use “self” if you don’t need to use it, in swift code “self” property of an instance that holds the instance itself. Most appear in an initializer, method of a class, or use like asynchronous.
//Before
Class ViewController: UIIVewController {
.
.
var strA: String?
var strB: Int?
override func viewDidLoad() {
super.viewDidLoad()
self.strA = "test str"
self.strB = 12
}
// After
Class ViewController: UIIVewController {
.
.
var strA: String?
var strB: Int?
override func viewDidLoad() {
super.viewDidLoad()
strA = "test str"
strB = 12
}
Or if you found this error below, it means you can fixing just add “self” to your code to fix it. usually I found when using “Dequeque.main.asyc” and etc.

Safe (bounds-checked) array to avoid crashes
Sometime when get error reload data array index example use tableview
get data from API but crash in reload condition use this code to help fixing crash.
Use array safe in tableview cell
cell.model = model?[safe: indexPath.row]
//Before
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(TableViewCell.self, for: indexPath)
cell.model = model?[indexPath.row]
return cell
}
//After
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(TableViewCell.self, for: indexPath)
cell.model = model?[safe: indexPath.row]
return cell
}
Empty count
Make is clean code use isEmpty, prefer checking isEmpty
over comparing count
to zero.
//Before
let stringArray: [String] = ["data1", "data2"]
if stringArray.count > 0 {
print("Action here")
}
//or
if stringArray.count == 0 {
print("Action here")
}
//After
let stringArray: [String] = ["data1", "data2"]
if !stringArray.isEmpty {
print("Action here")
}
//or
if stringArray.isEmpty {
print("Action here")
}
Remove all empty space from the string
It this better clean to remove the character from a string which is a space. generally people use `replacingOccurrences`, here’s another way.
//Before
let stringS = "1001 0921 3040"
let trimmedStringBefore = stringS.replacingOccurrences(of: " ", with: "")
print(trimmedStringBefore) // 100109213040
//After
let stringS = "1001 0921 3040"
let trimmedStringAfter = stringS.components(separatedBy: .whitespaces).joined()
print(trimmedStringAfter) // 100109213040
Make simple code
sometimes we need to explore more code in order to get more effective code, this is one I learned during code review. my leader tells a simpler code.
//Before
var newValue = "0123456789"
newValue.forEach { _ in
if newValue.count > 5 {
newValue.removeLast()
}
}
print(newValue) // 01234
//After
var newValue = "0123456789"
let betterNewValue = newValue.prefix(5)
print(betterNewValue) // 01234
When the endpoint needs a bool parameter
The backend requires a boolean parameter in the URL, such as https://example.com/auth?is_home=true.
However, when using the GET method, the boolean is automatically converted to 1 if true or 0 if false.
For example, if `false`, the URL becomes https://example.com/auth?is_home=0, and if `true`, it becomes https://example.com/auth?is_home=1.
To resolve this issue, change the data type of isHome
from boolean to string, i.e. String(isHome)
.
// Before
public struct Request {
let isHome: Bool
var parameters: [String: Any]? {
return [
"is_home": isHome
]
}
}
// After
public struct Request {
let isHome: Bool
var parameters: [String: Any]? {
return [
"is_home": String(isHome)
]
}
}
My Swift UI news app template has been sold on the CodeCanyon website.
https://codecanyon.net/item/news-feed-app-using-swiftui/43068768 😄

Reference:
- https://medium.com/geekculture/ios-engineers-perspective-on-code-smell-fa2f725f4483
- also my code :)
Thank you for reading! If you enjoyed it, please consider clapping 👏 and following for more updates! 🚀