在 Swift 中隐藏(跳过)print() 和 debugPrint() 的方法

The way to hide(skip) print() and debugPrint() in Swift

最近,我创建了两个 Swift 函数来覆盖 Swift 标准库中的 print(...)debugPrint(...)。我把这两个功能放在了项目范围内。

func debugPrint(_ items: Any..., separator: Swift.String = " ", terminator: Swift.String = "\n") -> ()
{
#if DEBUG
    typealias newDebugPrint = (_ : [Any], _ : Swift.String, _ : Swift.String) -> ()
    let castedDebugPrint = unsafeBitCast(Swift.debugPrint, to: newDebugPrint.self)
    castedDebugPrint(items, separator, terminator)
#else
// Do nothing...
#endif
}

func print(_ items: Any..., separator: Swift.String = " ", terminator: Swift.String = "\n") -> ()
{
#if DEBUG
    typealias newPrint = (_ : [Any], _ : Swift.String, _ : Swift.String) -> ()
    let castedPrint = unsafeBitCast(Swift.print, to: newPrint.self)
    castedPrint(items, separator, terminator)
#else
// Do nothing...
#endif
}

使用上面的功能可以让我们使用origin print(...)debugPrint(...),不用担心release build时输出大量消息。但是,在发布版本中使用它们真的安全吗?想知道这种覆盖背后的潜在风险吗?

如有任何想法,我们将不胜感激!

您不需要做所有这些...这实际上是同一件事:

func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    #if DEBUG
    items.forEach {
        Swift.print([=10=], separator: separator, terminator: terminator)        
    }
    #endif
}

您可能还想看看这个答案以进行更多讨论:

我看到您正在使用 Swift,那么打印是完全安全的,即使对于 AppStore 版本也是如此。您不会被拒绝,也不会存在安全风险。

与类似的 NSLog 不同,

print 不会在用户可见的任何地方生成任何日志(例如在 Xcode 设备控制台中)。因此,无需担心发布版本中的大量消息输出。

有关 print 和 NSLog 之间区别的更多信息:Swift:print() vs println() vs NSLog()