今天在檢視代碼察郁,發(fā)現(xiàn)一些問題,順便貼出來美旧,第一篇簡書文章
濫用guard
首先看一下官方對guard關(guān)鍵字的說明
Early Exit
A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.”
摘錄來自: Apple Inc. “The Swift Programming Language (Swift 3 beta)”怀大。 iBooks. https://itun.es/us/k5SW7.l
而下面的例子并不是對異常情況進(jìn)行判斷,所以該場景下應(yīng)該使用if
或switch
guard orderData["workOrderType"].numberValue == OrderType.ServiceOrder.rawValue else {
orderCell.orderType = .WorkOrder
orderCell.configCell(orderData, indexPatch: indexPath)
return orderCell
}
使用硬代碼(魔鬼數(shù)字)
cell.remarkLabel.preferredMaxLayoutWidth = (screenWidth - 320) + 304
代碼擠成一坨
下面的代碼有幾個問題
- 代碼擠成一坨
- 用代碼去生成按鈕(不推薦)
- 用代碼去生成按鈕的目的實(shí)際上是想設(shè)置按鈕的顏色逼友,這個可能通過
tintColor
很方便地處理
let cancelButton = UIButton(type: .System)
cancelButton.frame = CGRectMake(0, 0, 42, 20)
cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
cancelButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
cancelButton.setTitleColor(UIColor.colorWithHexString("#29b6f6"), forState: .Normal)
picker.setCancelButton(UIBarButtonItem(customView: cancelButton))
let doneButton = UIButton(type: .System)
doneButton.frame = CGRectMake(0, 0, 50, 20)
doneButton.setTitle(doneButtonTitle, forState: .Normal)
doneButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
doneButton.setTitleColor(UIColor.colorWithHexString("#29b6f6"), forState: .Normal)
picker.setDoneButton(UIBarButtonItem(customView: doneButton))
比較好的代碼應(yīng)該這樣(忽略selector的處理)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: nil)
cancelButton.tintColor = UIColor.colorWithHexString("#29b6f6")
picker.setCancelButton(cancelButton)
let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: nil)
doneButton.tintColor = UIColor.colorWithHexString("#29b6f6")
picker.setDoneButton(doneButton)
類型初始化有誤
下面代碼中的變量不可能為浮點(diǎn)型精肃,卻聲明為浮點(diǎn)型
var currentPage = 1.0
var pageSize = 10.0
毫無意義的重載
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
Bean使用復(fù)數(shù)
Bean是抽象的,不應(yīng)該為復(fù)數(shù)
public static class WorkOrdersBean