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).
Jua*_*ero 24
迅速:
NSLog("this will print with dates")
Run Code Online (Sandbox Code Playgroud)
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)
这是一个建议的功能,你可以使用而不是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)
| 归档时间: |
|
| 查看次数: |
14296 次 |
| 最近记录: |