Remove println() for release version iOS Swift

前端 未结 19 1518
被撕碎了的回忆
被撕碎了的回忆 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:46

    Even simpler: take advantage of the fact that asserts are removed from release builds and only from there call the print. This removes all log calls (yes, even the calls to Log.da) as they are empty when building for release.

    But I also heard that prints are removed for release builds, but not been able to find it in writing. So for now, I am using something like this Log below. I have a more meaty version on GitHub with emojis (for readability) and log topics (for consistency):

    https://github.com/Gatada/JBits/blob/master/Project/Utility/Log.swift

    public enum Log {
    
        /// A date formatter used to create the timestamp in the log.
        ///
        /// This formatter is only created if it is actually used, reducing the
        /// overhead to zero.
        static var formatter: DateFormatter?
    
        // MARK: - API
    
        /// Call to print message in debug area.
        ///
        /// Asserts are removed in release builds, which make
        /// the function body empty, which caused all calls to
        /// be removed as well.
        ///
        /// Result is zero overhead for release builds.
        public static func da(_ message: String) {
            assert(debugAreaPrint(message))
        }
    
        // MARK: - Helpers
    
        /// The function that actually does the printing. It returns `true` to
        /// prevent the assert from kicking in on debug builds.
        private static func debugAreaPrint(_ message: String) -> Bool {
            print("\(timestamp) - \(message)")
            return true
        }
    
        /// Creates a timestamp used as part of the temporary logging in the debug area.
        static private var timestamp: String {
    
            if formatter == nil {
                formatter = DateFormatter()
                formatter!.dateFormat = "HH:mm:ss.SSS"
            }
    
            let date = Date()
            return formatter!.string(from: date)
        }
    }
    

    In code:

    Log.da("This is only handled in a debug build.")
    

    Seen in the Xcode debug area only when running a debug build:

    13:36:15.047 - This is only handled in a debug build.

提交回复
热议问题