首页 > 解决方案 > 在 Swift 中隐藏(跳过)print() 和 debugPrint() 的方法

问题描述

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

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(...)并且不用担心发布构建时会输出大量消息。但是,它们在发布版本中使用真的安全吗?想知道这个覆盖背后的任何潜在风险吗?

任何想法将不胜感激!

标签: iosswiftstdoutstderr

解决方案


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

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

您可能还想看看这个答案进行更多讨论:https ://stackoverflow.com/a/38335438/6257435


推荐阅读