在C/C++/Objective C中,可以使用编译器预处理器定义宏。此外,您可以使用编译器预处理器包含/排除代码的某些部分。

#ifdef DEBUG
    // Debug-only code
#endif

Swift中有类似的解决方案吗?


当前回答

这是基于Jon Willis的答案,该答案依赖于断言,该断言仅在调试编译中执行:

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

我的用例是记录打印语句。以下是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)" )

打印:

Log: 0.0

看起来Swift 4完全消除了函数调用。

其他回答

如Apple Docs中所述

Swift编译器不包含预处理器。相反,它利用编译时属性、构建配置和语言特性来实现相同的功能。因此,在Swift中不导入预处理器指令。

我已经通过使用自定义构建配置实现了我想要的目标:

转到项目/选择目标/构建设置/搜索自定义标志对于所选目标,使用-D前缀(不带空格)为调试和发布设置自定义标志为您的每个目标执行以上步骤

以下是检查目标的方法:

#if BANANA
    print("We have a banana")
#elseif MELONA
    print("Melona")
#else
    print("Kiwi")
#endif

使用Swift 2.2测试

马特回答的Swift 5更新

let dic = ProcessInfo.processInfo.environment
if dic["TRIPLE"] != nil {
// ... do your secret stuff here ...
}

XCODE 9及以上

#if DEVELOP
    //print("Develop")
#elseif PRODUCTION
    //print("Production")
#else
    //
#endif

莫伊尼昂的回答很好。这是另一条信息,以防有帮助,

#if DEBUG
    let a = 2
#else
    let a = 3
#endif

您可以像下面这样否定宏,

#if !RELEASE
    let a = 2
#else
    let a = 3
#endif

这是基于Jon Willis的答案,该答案依赖于断言,该断言仅在调试编译中执行:

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

我的用例是记录打印语句。以下是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)" )

打印:

Log: 0.0

看起来Swift 4完全消除了函数调用。