Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 and would appreciate guidance. is there a way to do this globally, or do I need to surround every println() with #IF DEBUG/#ENDIF statements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
765 views
Welcome To Ask or Share your Answers For Others

1 Answer

The simplest way is to put your own global function in front of Swift's println:

func println(object: Any) {
    Swift.println(object)
}

When it's time to stop logging, just comment out the body of that function:

func println(object: Any) {
    // Swift.println(object)
}

Or you can make it automatic by using a conditional:

func println(object: Any) {
    #if DEBUG
        Swift.println(object)
    #endif
}

EDIT In Swift 2.0 println is changed to print. Unfortunately it now has a variadic first parameter; this is cool, but it means you can't easily override it because Swift has no "splat" operator so you can't pass a variadic in code (it can only be created literally). But you can make a reduced version that works if, as will usually be the case, you are printing just one value:

func print(items: Any..., separator: String = " ", terminator: String = "
") {
    Swift.print(items[0], separator:separator, terminator: terminator)
}

In Swift 3, you need to suppress the external label of the first parameter:

func print(_ items: Any..., separator: String = " ", terminator: String = "
") {
    Swift.print(items[0], separator:separator, terminator: terminator)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...