Why print() in Swift does not log the time stamp as NSLog in objective C Why print() in Swift does not log the time stamp as NSLog in objective C ios ios

Why print() in Swift does not log the time stamp as NSLog in objective C


Because print is not NSLog. It is as simple as that.

NSLog is a logging tool in Foundation that writes to the Apple System Log facility which appears on the console.

print(…) is a print function in the Swift Standard Library that writes to standard out, which appears on the console in debug sessions.

You could add Date() to your print parameter to print the current time and date. (Or Date().description(with: Locale.current) to get it in your local time zone.)

Or you could just use NSLog which is available in Swift too (if you import Foundation).


Swift:

NSLog("this will print with dates")


This one just outputs a simple timestamp, but can be easily modified to include additional text if you want.

Additionally, it relies on a lazy DateFormatter to avoid expensive initializations.

import Foundationclass Timestamp {    lazy var dateFormatter: DateFormatter = {        let formatter = DateFormatter()        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "        return formatter    }()    func printTimestamp() {        print(dateFormatter.string(from: Date()))    }}let timestamp = Timestamp()timestamp.printTimestamp() // 2018-07-05 12:57:08.725timestamp.printTimestamp() // 2018-07-05 12:57:08.727 (uses the same formatter)