Remove println() for release version iOS Swift

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

    Updated for Swift 4.x:

    With Swift 2.0/3.0 and Xcode 7/8 now out of beta, there have been some changes to how you disable the print function in release builds.

    There are some important points mentioned by @matt and @Nate Birkholz above that are still valid.

    1. The println() function has been replaced by print()

    2. To use the #if DEBUG macro then you have to define the "Swift Compiler - Custom Flags -Other Flags" to contain the value -D DEBUG

    3. I would recommend overriding the Swift.print() function in the global scope so that you can use the print() function as normal in your code, but it will remove output for non-debug builds. Here is a function signature that you can add at the global scope to do this in Swift 2.0/3.0:

      func print(items: Any..., separator: String = " ", terminator: String = "\n") {
      
          #if DEBUG
      
          var idx = items.startIndex
          let endIdx = items.endIndex
      
          repeat {
              Swift.print(items[idx], separator: separator, terminator: idx == (endIdx - 1) ? terminator : separator)
              idx += 1
          }
          while idx < endIdx
      
          #endif
      }
      

    Note: We have set the default separator to be a space here, and the default terminator to be a newline. You can configure this differently in your project if you would like.

    Hope this helps.

    Update:

    It is usually preferable to put this function at the global scope, so that it sits in front of Swift's print function. I find that the best way to organize this is to add a utility file to your project (like DebugOptions.Swift) where you can place this function at the global scope.

    As of Swift 3 the ++ operator will be deprecated. I have updated the snippet above to reflect this change.

提交回复
热议问题