【问题标题】:The way to hide(skip) print() and debugPrint() in SwiftSwift 中隐藏(跳过)print() 和 debugPrint() 的方法
【发布时间】:2021-03-26 18:45:13
【问题描述】:

最近,我创建了两个 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
}

使用上面的函数可以让我们使用originprint(...)debugPrint(...),并且不用担心发布构建时会输出大量消息。但是,它们在发布版本中使用真的安全吗?想知道此覆盖背后的任何潜在风险吗?

任何想法将不胜感激!

【问题讨论】:

    标签: ios swift stdout stderr


    【解决方案1】:

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

    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

    【讨论】:

    • 谢谢@DanMag,答案很有用。我将使用上面的代码更新我的实现。
    【解决方案2】:

    我看到您使用的是 Swift,那么 print 是完全安全的,即使对于 AppStore 构建也是如此。您不会被拒绝,也不会带来安全风险。

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

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

    【讨论】:

    • 感谢您的建议。我会研究那个。
    猜你喜欢
    • 2021-06-24
    • 2015-12-03
    • 2014-11-21
    • 2010-11-13
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多