anjani kp
anjani kp

Reputation: 63

Logtrace equivalent in Swift Language - iPhone

Is there any logtrace equivalent in Swift language?

I do not wish to use the bridge-header concept.

The objective I'm trying to achieve is that I want println statements to write to console during dev/staging phase of the app and with the flip of a switch, console printing should be stopped just before pushing to app store.

On another thought-line, does println automatically stop printing on the console during distribution? (may be a bonus of migrating to Swift)

Upvotes: 1

Views: 177

Answers (1)

Martin R
Martin R

Reputation: 539725

You could take a similar approach as the built-in assert() function, which is explained in the Swift blog:

The logTrace function takes an "auto-closure" as the first argument:

func logTrace(message: @autoclosure () -> String, file: StaticString = __FILE__, line: UWord = __LINE__) {
        #if DEBUG
            let msg = message()
            println("\(file):\(line): \(msg)")
        #endif
}

Example usage:

let height = 13
logTrace ( "height = \(height)" )
// Output: /Users/.../main.swift:14: height = 13

To make this work you have to add "-DDEBUG" to the "Other Swift Flags" for the debug configuration, compare

enter image description here

The advantage of this method is that (as with assert()) the block is not evaluated at all in the Release configuration, where "DEBUG" is not defined, e.g. in

logTrace ( someFunctionReturningAString() )

the function would not be called in the Release configuration, so any side-effects or performance overhead is avoided.


Update for Swift 2:

func logTrace(@autoclosure message: () -> String, file: String = __FILE__, line: Int = __LINE__) {
    #if DEBUG
        let msg = message()
        print("\(file):\(line): \(msg)")
    #endif
}

Update for Swift 3:

func logTrace(_ message: @autoclosure () -> String, file: String = #file, line: Int = #line) {
    #if DEBUG
        let msg = message()
        print("\(file):\(line): \(msg)")
    #endif
}

Upvotes: 3

Related Questions