0

Recently, I have created two Swift functions to override print(...) and debugPrint(...) from Swift standard library. I put these two functions in the project scope.

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
}

Using the functions above can let us use origin print(...) and debugPrint(...) and no need to worry about massive message output in release build. But, are they really safe to use in release build? Would like to know any potential risk behind this overridden?

Any thought would be appreciate!

2 Answers2

0

You don't need to do all of that... this will be effectively the same thing:

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

You might also want to take a look at this answer for a little more discussion: https://stackoverflow.com/a/38335438/6257435

DonMag
  • 69,424
  • 5
  • 50
  • 86
  • Thank you @DanMag, the answer is useful. I will update my implementation with the above code. – CHIEN-MING LEE Mar 27 '21 at 05:43
  • compile error `Invalid redeclaration of 'print(_:separator:terminator:)'` – Yiming Dong Apr 16 '23 at 03:55
  • @YimingDong - if you get that compile error, that means you already have `print()` defined somewhere else in your project. Search your source for `func print` to find it. Note that if you have 3rd-party code (such as pods) it may be defined where you haven't yet seen it. If you create a brand new project and paste that code, you will NOT get the error. – DonMag Apr 16 '23 at 13:02
  • Thanks @DonMag, yeah my bad, found it in 3rd party code. – Yiming Dong Apr 17 '23 at 05:24
0

I see you are using Swift, then print is completely safe, even for AppStore builds. You are not going to be rejected and it's not a security risk either.

print, unlike similar NSLog, is not going to produce any logs anywhere that would be visible to the user (e.g. in Xcode Device Console). So there is never any need to worry about massive message output in release build.

More info on the difference between print and NSLog: Swift: print() vs println() vs NSLog()

Daniel Lyon
  • 1,499
  • 10
  • 15