今天在检视代码,发现一些问题,顺便贴出来,第一篇简书文章
滥用guard
首先看一下官方对guard关键字的说明
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
而下面的例子并不是对异常情况进行判断,所以该场景下应该使用if
或switch
guard orderData["workOrderType"].numberValue == OrderType.ServiceOrder.rawValue else {
orderCell.orderType = .WorkOrder
orderCell.configCell(orderData, indexPatch: indexPath)
return orderCell
}
使用硬代码(魔鬼数字)
cell.remarkLabel.preferredMaxLayoutWidth = (screenWidth - 320) + 304
代码挤成一坨
下面的代码有几个问题
- 代码挤成一坨
- 用代码去生成按钮(不推荐)
- 用代码去生成按钮的目的实际上是想设置按钮的颜色,这个可能通过
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))
比较好的代码应该这样(忽略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)
类型初始化有误
下面代码中的变量不可能为浮点型,却声明为浮点型
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使用复数
Bean是抽象的,不应该为复数
public static class WorkOrdersBean