Search code examples
iosswiftstdoutstderr

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


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!


Solution

  • 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