Remove println() for release version iOS Swift

前端 未结 19 1522
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 15:55

I would like to globally ignore all println() calls in my Swift code if I am not in a Debug build. I can\'t find any robust step by step instructions for this a

19条回答
  •  伪装坚强ぢ
    2020-11-29 16:51

    Here is a function that I use, which works perfectly in Swift 3:

    func gLog( _ object: @autoclosure() -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line)
        {
        #if DEBUG
            let value = object()
            let stringRepresentation: String
    
            if let value = value as? CustomDebugStringConvertible
                {
                stringRepresentation = value.debugDescription
                }
            else if let value = value as? CustomStringConvertible
                {
                stringRepresentation = value.description
                }
            else
                {
                fatalError("gLog only works for values that conform to CustomDebugStringConvertible or CustomStringConvertible")
                }
    
            let fileURL = NSURL(string: file)?.lastPathComponent ?? "Unknown file"
            let queue = Thread.isMainThread ? "UI" : "BG"
        let gFormatter = DateFormatter()
        gFormatter.dateFormat = "HH:mm:ss:SSS"
            let timestamp = gFormatter.string(from: Date())
    
            print("✅ \(timestamp) {\(queue)} \(fileURL) > \(function)[\(line)]: " + stringRepresentation + "\n")
        #endif
        }
    

    Here is an example of the output it generates:

    Explanation:

    • the green checkmark is used to enable you to quickly see your print (gLog) messages in the console, where they can sometimes get lost in a sea of other messages

    • the time/date stamp

    • the thread it is being run on -- in my case it is either the MainThread (which I call UI), or not the MainThread (which I call BG, for background thread)

    • the name of the file that the gLog message resides in

    • the function within the file that the gLog message resides in

    • the line number of the gLog message

    • the actual gLog message you would like to print out

    Hope this is useful to someone else!

提交回复
热议问题