Swift:print()vs println()vs NSLog()

本文翻译自:Swift: print() vs println() vs NSLog()

What's the difference between print , NSLog and println and when should I use each? printNSLogprintln之间的区别是什么?我应该在何时使用它们?

For example, in Python if I wanted to print a dictionary, I'd just print myDict , but now I have 2 other options. 例如,在Python中,如果我想打印字典,我只print myDict ,但现在我有2个其他选项。 How and when should I use each? 我应该如何以及何时使用它们?


#1楼

参考:https://stackoom.com/question/1kt5f/Swift-print-vs-println-vs-NSLog


#2楼

A few differences: 一些差异:

  1. print vs println : print vs println

    The print function prints messages in the Xcode console when debugging apps. 调试应用程序时, print功能在Xcode控制台中打印消息。

    The println is a variation of this that was removed in Swift 2 and is not used any more. println是Swift 2中删除的变体,不再使用了。 If you see old code that is using println , you can now safely replace it with print . 如果您看到使用println旧代码,现在可以使用print安全地替换它。

    Back in Swift 1.x, print didn't add newline characters at the end of the printed string, whereas println did. 回到Swift 1.x, print没有在打印字符串的末尾添加换行符,而println没有。 But nowadays, print always adds the newline character at the end of the string, and if you don't want it to do that, supply a terminator parameter of "" . 但是现在, print始终在字符串的末尾添加换行符,如果您不希望它这样做,请提供terminator参数""

  2. NSLog : NSLog

    • NSLog is slower; NSLog比较慢;

    • NSLog adds a timestamp and identifier to the output, whereas print will not; NSLog为输出添加时间戳和标识符,而print则不会;

    • NSLog statements appear in both the device's console and debugger's console whereas print only appears in the debugger console. NSLog语句出现在设备的控制台和调试器的控制台中,而print仅出现在调试器控制台中。

    • NSLog uses printf -style format strings, eg NSLog使用printf样式的格式字符串,例如

       NSLog("%0.4f", CGFloat.pi) 

      that will produce: 会产生:

      2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416 2017-06-09 11:57:55.642328-0700 MyApp [28937:1751492] 3.1416

  3. Effective iOS 10/macOS 10.12, there is a third alternative, os_log , part of the "unified logging" system (see WWDC 2016 video Unified Logging and Activity Tracing ). 有效的iOS 10 / macOS 10.12,还有第三种选择, os_log ,是“统一日志记录”系统的一部分(参见WWDC 2016视频统一记录和活动跟踪 )。

    • You must import os.log before using os_log function: 在使用os_log函数之前必须导入os.log

       import os.log 
    • Like NSLog , os_log will output messages to both the Xcode debugging console and the device console, too NSLog一样, os_log也会向Xcode调试控制台和设备控制台输出消息

    • You can now control the "subsystem" and "category" fields available in the Console app. 您现在可以控制Console应用程序中可用的“子系统”和“类别”字段。 For example: 例如:

       let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network") os_log("url = %@", log: log, url.absoluteString) 

      When you observe the app via the external Console app, you can not only add these columns to the main view, but you can filter on the basis of these. 当您通过外部控制台应用程序观察应用程序时,您不仅可以将这些列添加到主视图中,还可以根据这些列进行过滤。 It's very useful when wanting to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app; 当想要将调试消息与(a)其他子系统代表您的应用程序生成的消息区分开来时,它非常有用; or (b) messages from other categories or types. 或(b)来自其他类别或类别的讯息。

    • You can specify different types of logging messages, either .info , .debug , .error , .fault (or .default ): 您可以指定不同类型的日志消息, .info.debug.error.fault (或.default ):

       os_log("web service did not respond", type: .error) 

      So, if using the external Console app, you can choose to only see messages of certain categories (eg only show debugging messages if you choose "Include Debug Messages" on the Console "Action" menu). 因此,如果使用外部控制台应用程序,您可以选择仅查看某些类别的消息(例如,如果您在控制台“操作”菜单上选择“包含调试消息”,则仅显示调试消息)。 These settings also dictate many subtle issues details about whether things are logged to disk or not. 这些设置还规定了许多关于事物是否记录到磁盘的细微问题。 See WWDC video for more details. 有关详细信息,请参阅WWDC视频。

    • You cannot use string interpolation when using os_log . 使用os_log时不能使用字符串插值。 For example you cannot do: 例如,您不能这样做:

       os_log("foo \\(url.absoluteString)") 

      You would have to do: 你必须这样做:

       os_log("url = %@", url.absoluteString) 
    • One of the reasons for the above limitation is to support data privacy. 上述限制的原因之一是支持数据隐私。 Primitive data types (eg numbers) are public by default and objects (eg strings) are private by default. 默认情况下,原始数据类型(例如数字)是公共的,对象(例如字符串)是私有的。 In the previous example where you logged the URL, if the app were invoked from the device itself and you were watching from your Mac's Console app, you'd see: 在上一个记录URL的示例中,如果从设备本身调用了应用程序并且您正在从Mac的控制台应用程序中观看,则会看到:

      url = <private> url = <private>

      If you wanted to see it from external device, you'd have to do: 如果你想从外部设备看到它,你必须这样做:

       os_log("url = %{public}@", url.absoluteString) 
    • Note, NSLog now uses the unified notification system behind the scenes, but with the following caveats: 注意, NSLog现在使用幕后的统一通知系统,但有以下警告:

      • You cannot control the subsystem or category or log type; 您无法控制子系统或类别或日志类型;

      • It does not support privacy settings. 它不支持隐私设置。

Bottom line, print is sufficient for simple tasks, but NSLog is useful because it includes timestamp information for you. 底线, print就足以完成简单的任务,但NSLog非常有用,因为它包含了您的时间戳信息。

The power of os_log comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. 在调试必须在Xcode之外进行测试的iOS应用程序时, os_log的强大功能os_log For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle . 例如,在测试后台iOS应用程序进程(如后台提取)时,连接到Xcode调试器会更改应用程序生命周期 So, you frequently will want to test on physical device, running app from device itself, not starting the app from Xcode's debugger. 因此,您经常需要在物理设备上进行测试,从设备本身运行应用程序,而不是从Xcode的调试器启动应用程序。 Unified logging let's you still watch your iOS device os_log statements from the macOS Console app. 统一日志记录让您仍然可以从macOS控制台应用程序中查看iOS设备的os_log语句。


#3楼

If you're using Swift 2 , now you can only use print() to write something to the output. 如果您正在使用Swift 2 ,现在只能使用print()向输出写入内容。

Apple has combined both println() and print() functions into one. Apple将println()print()函数合二为一。

Updated to iOS 9 已更新至iOS 9

By default, the function terminates the line it prints by adding a line break. 默认情况下,该函数通过添加换行符来终止它打印的行。

print("Hello Swift")

Terminator 终结者

To print a value without a line break after it, pass an empty string as the terminator 要在其后打印没有换行符的值,请将空字符串作为终止符传递

print("Hello Swift", terminator: "")

Separator 分隔器

You now can use separator to concatenate multiple items 您现在可以使用分隔符来连接多个项目

print("Hello", "Swift", 2, separator:" ")

Both

Or you could combine using in this way 或者你可以用这种方式结合使用

print("Hello", "Swift", 2, separator:" ", terminator:".")

#4楼

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)! 而且,Swift 2有debugPrint() (和CustomDebugStringConvertible协议)!

Don't forget about debugPrint() which works like print() but most suitable for debugging . 不要忘记debugPrint() ,它的工作方式与print()类似,但最适合调试

Examples: 例子:

  • Strings 字符串
    • print("Hello World!") becomes Hello World print("Hello World!")成为Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!) debugPrint("Hello World!")变成"Hello World" (行情!)
  • Ranges 范围
    • print(1..<6) becomes 1..<6 print(1..<6)变为1..<6
    • debugPrint(1..<6) becomes Range(1..<6) debugPrint(1..<6)变为Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol. 任何类都可以通过CustomDebugStringConvertible协议自定义其调试字符串表示。


#5楼

There's another method called dump() which can also be used for logging: 还有另一个名为dump()方法,它也可用于记录:

 func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int) 

Dumps an object's contents using its mirror to standard output. 使用镜像将对象的内容转储到标准输出。

From Swift Standard Library Functions 来自Swift标准库函数


#6楼

To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection. 为了增加Rob的答案,自iOS 10.0以来,Apple推出了一个全新的“统一记录”系统,取代现有的记录系统(包括ASL和Syslog,NSLog),并且由于其新技术在内,也超越了现有的记录方法。记录数据压缩和延迟数据收集。

From Apple : 来自Apple

The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. 统一日志记录系统提供单一,高效,高性能的API,用于捕获跨系统所有级别的消息传递。 This unified system centralizes the storage of log data in memory and in a data store on disk. 该统一系统将日志数据的存储集中在内存和磁盘上的数据存储中。

Apple highly recommends using os_log going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. Apple强烈建议使用os_log记录各种消息,包括信息,调试,错误消息,因为与以前的日志记录系统相比,它的性能大大提高,并且集中式数据收集允许开发人员方便地进行日志和活动检查。 In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen. 实际上,新系统的占用空间可能很小,如果插入日志记录命令,干扰错误发生的时间,它就不会导致“观察者效应”。

活动跟踪的性能,现在是新的统一记录系统的一部分

You can learn more about this in details here . 您可以在此处详细了解此信息。

To sum it up: use print() for your personal debugging for convenience (but the message won't be logged when deployed on user devices). 总结一下:为方便起见,请使用print()进行个人调试(但在用户设备上部署时不会记录消息)。 Then, use Unified Logging ( os_log ) as much as possible for everything else. 然后,尽可能使用统一日志记录( os_log )。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值