swift代码优化

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"
}
7. 模块化代码,使用私有Cocoapods repository. 让不同模块以Framework或则.a文件的形式在项目里使用。如此每次编译的时候就只需要编译自己模块下的代码。其他模块的代码将会被编译后缓存,不需要重复编译