为什么swift中的print()不会将时间戳记录为目标C中的NSLog

Mah*_*dam 37 objective-c nslog ios swift

从Objective C的背景开始,当我使用NSLog()它时,它的前缀是带有日期时间戳的文本,但是当我print()在Swift上使用时,它只打印文本

所以有一种方法可以让它打印时间戳,或者我做错了什么?

Her*_*ker 46

因为print不是NSLog.它是如此简单.

NSLog 是Foundation中的一个日志工具,它写入控制台上显示的Apple System Log工具.

print(…) 是Swift标准库中的一个打印函数,它写入标准输出,在调试会话中显示在控制台上.

你可以添加Date()到您的print参数,打印当前的时间和日期.(或者Date().description(with: Locale.current)在当地时区获取它.)

或者您也可以使用NSLogSwift中可用的(如果您导入Foundation).

  • 谢谢我试过`NSLog`它的工作原理我将在需要显示时间戳的情况下使用它 (2认同)

Jua*_*ero 24

迅速:

NSLog("this will print with dates")
Run Code Online (Sandbox Code Playgroud)

  • 但不在 Playground 中打印 (2认同)

Cod*_*der 10

这只是输出一个简单的时间戳,但如果需要,可以轻松修改以包含其他文本。

此外,它依赖于lazy DateFormatter避免昂贵的初始化。

import Foundation

class 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.725
timestamp.printTimestamp() // 2018-07-05 12:57:08.727 (uses the same formatter)
Run Code Online (Sandbox Code Playgroud)


dav*_*d72 5

这是一个建议的功能,你可以使用而不是print()

func printLog(log: AnyObject?) {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
    print(formatter.stringFromDate(NSDate()), terminator: "")
    if log == nil {
        print("nil")
    }
    else {
        print(log!)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 创建NSDateFormatter的实例代价很高.因此,理想情况下,`formatter`只需要在方法之外创建一次,以避免每次调用方法时调用NSDateFormatter(). (13认同)