#ifdef replacement in the Swift language

前端 未结 17 1875
名媛妹妹
名媛妹妹 2020-11-22 10:35

In C/C++/Objective C you can define a macro using compiler preprocessors. Moreover, you can include/exclude some parts of code using compiler preprocessors.

         


        
17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 11:39

    This builds on Jon Willis's answer that relies upon assert, which only gets executed in Debug compilations:

    func Log(_ str: String) { 
        assert(DebugLog(str)) 
    }
    func DebugLog(_ str: String) -> Bool { 
        print(str) 
        return true
    }
    

    My use case is for logging print statements. Here is a benchmark for Release version on iPhone X:

    let iterations = 100_000_000
    let time1 = CFAbsoluteTimeGetCurrent()
    for i in 0 ..< iterations {
        Log ("⧉ unarchiveArray:\(fileName) memoryTime:\(memoryTime) count:\(array.count)")
    }
    var time2 = CFAbsoluteTimeGetCurrent()
    print ("Log: \(time2-time1)" )
    

    prints:

    Log: 0.0
    

    Looks like Swift 4 completely eliminates the function call.

提交回复
热议问题