swift代码优化
更加详细的内容会同步更新在GitHub项目ios-Tips中
影响编译速度的代码
测试编译速度可已使用该工具
1.自动类型推导的代码
var model : UILabel?
var cat : String?
var name : String?
var number : Int?
//build time : 8740.3ms
func sendData() {
let parameter = ["model" : model?.text ?? "",
"cat" : cat ?? "",
"name" : name ?? "",
"number" : number ?? 0,
"dog" : "dog"]
print("send request with parameter:\(parameter)")
}
//build time: 3235.4ms
let parameter : [String : AnyObject] = ["model" : model?.text ?? "",
"cat" : cat ?? "",
"name" : name ?? "",
"number" : number ?? 0,
"dog" : "dog"]
2.Any 或 AnyObjec 、any?
//build time: 200.3ms
let parameter : [String : String] = ["model" : model?.text ?? "",
"cat" : cat ?? "",
"name" : name ?? "",
"number" : "\(number ?? 0)",
"dog" : "dog"]
3.运算时使用可选值
//build time : 9804ms
func calculateSize(view : UIView?) -> CGSize{
return CGSize(width: 10 + (view?.bounds.width ?? 0) + (view?.bounds.height ?? 0) + 22, height: 20)
}
//build time : 172ms
func calculateSize(view : UIView?) -> CGSize{
let width = view?.bounds.width ?? 0
let height = view?.bounds.height ?? 0
return CGSize(width: 10 + width + height + 22, height: 20)
}
4. 三目运算符(Bool ? a : b)
5. 集合运算使用+或+=
//build time 1400.6ms
func arrPlusOperatos() {
let arr1 = [1,2,3]
let arr2 = [3,4,5]
result += arr1 + arr2 + [10]
}
//build time 8.6ms
func arrPlusOperatos() {
let arr1 = [1,2,3]
let arr2 = [3,4,5]
result.appendContentsOf(arr1)
result.appendContentsOf(arr2)
result.appendContentsOf([10])
}
6. String 合并使用 +
//build time 79.4ms
func strPlusOperatos() {
let str1 = "1234567890"
let str2 = "ABCDEFGHIJK"
result += str1 + str2 + "hello world"
}
//build time 6ms
func strPlusOperatos() {
let str1 = "1234567890"
let str2 = "ABCDEFGHIJK"
result = "\(str1)\(str2)hello world"
}