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.

//BeforeClass 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")
}
}
}
// Afterclass 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 appears 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
}
//Afterfunc 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")
}
//orif stringArray.count == 0 {
print("Action here")
}
//After
let stringArray: [String] = ["data1", "data2"]
if !stringArray.isEmpty {
print("Action here")
}
//orif stringArray.isEmpty {
print("Action here")
}

Remove all empty space from string

This better clean to remove the character from a string which is a space. generally people use `replacingOccurrences`, here’s another way.

//Beforelet stringS = "1001 0921 3040"let trimmedStringBefore = stringS.replacingOccurrences(of: " ", with: "")print(trimmedStringBefore) // 100109213040//Afterlet 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
//Aftervar newValue = "0123456789"
let betterNewValue = newValue.prefix(5)
print(betterNewValue) // 01234

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store