How to print out the method name and line number in swift - swift
Here is an example of what I want to do:
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
let nm = NetworkModel()
nm.sendlog("file name :AppDelegate , line number : 288", info: " Failed to register: \(error)")
}
current scenario i done that hard coded value line number and file name . but is it possible to programatically pick line number and file name .
Literal Type Value
#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.
#dsohandle UnsafeMutablePointer The dso handle.
Example
print("Function: \(#function), line: \(#line)")
With default values in parameters you can also create a function
public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {
print("\(message) called from \(function) \(file):\(line)")
}
which can be used like this
track("enters app")
In Swift 2.1
Literal Type Value
__FILE__ String The name of the file in which it appears.
__LINE__ Int The line number on which it appears.
__COLUMN__ Int The column number in which it begins.
__FUNCTION__ String The name of the declaration in which it appears.
for more info see the documentation
You can use #function, #file, #line
Here is the implementation of log method in swift : https://github.com/InderKumarRathore/SwiftLog
Below is the snippet
public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
#if DEBUG
let className = (fileName as NSString).lastPathComponent
print("<\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
#endif
}
For swift 4 and swift 5:
func printLog(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
#if DEVELOPMENT
let className = file.components(separatedBy: "/").last
print(" ❌ Error ----> File: \(className ?? ""), Function: \(function), Line: \(line), Message: \(message)")
#endif
}
// "❌ Error ----> File: classNameViewController.swift, function: functionName(), Line: 123, Message: messageError"
Example Logging Code (TL;DR)
import os.log
#available(OSX 11.0, iOS 14.0, *)
extension Logger {
private static var subsystem = Bundle.main.bundleIdentifier!
/// Logs the payment flows like Apple Pay.
#available(OSX 11.0, iOS 14.0, *)
static let payments = Logger(subsystem: subsystem, category: "payments")
}
static func DLog(message: StaticString, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, column: UInt = #column, category: String, type: OSLogType = .info, bundle: Bundle = .main) {
// This method is only for iOS 14+
if #available(OSX 11.0, iOS 14.0, *) {
Logger.payments.debug("\(file) : \(function) : \(line) : \(column) - \(message, privacy: .private)")
// This makes the message unreadable without a debugger attached.
} else {
// Fallback on earlier versions
let customLog = OSLog(subsystem: bundle.bundleIdentifier!,
category: category)
// IMPORTANT: I have assumed here that you only print out non-sensitive data! Using %{private}# or %{public}# in an interpolated string is not portable to `Logger`!
os_log(message, log: customLog, type: type)
// Unfortunately this legacy API doesn't support non-StaticString logs. :(
}
}
Note that you may need to rework this code for more flexibility over private/public access levels - os_log and Logger don’t handle privacy levels in the same way. This is just to show how to use the API if you don’t add os_log privacy levels in message.
Apple recommend using OS Logging which is why I have used this approach rather than print statements. I added this answer because of the new Logger API in iOS 14 that also enables string interpolation.
Motivation
I think the answers here solve the question for < iOS 14, but they can be improved further for memory efficiency since this Debug Logging function will likely be used all across a codebase in iOS 14+ (new Logger API). Apple recommend using OS Logging which is why I have used this approach rather than print statements (although these will still work).
These are minor improvements but I think they can help because even minor improvements add up. In fact, the Swift Standard Library uses these optimizations everywhere they can)! These optimisations are contributing factors to the incredible memory efficiency of Swift despite being a high-level language (and part of great API Design!). (-:
Because this function would probably fit well as part of a generalized (OS) Logging service, I have also included considerations I make when logging within apps. I think these could help you when logging for debugging purposes (I answered this question because it was probably for debug logging!).
Improvements
I prefer to use UInt in certain situations if I know the Int is going to be positive, and any edge case crashes are unlikely. Note, I don't use UInt when interfacing with Foundation classes that use Int types for this reason. This allocates less memory at runtime and I find being more specific also helps me understand the code better.
I prefer to use StaticString where I know the string is known at compile-time. From the docs, StaticString only provides low-level access to String contents and is immutable. Thus only use it where appropriate. Even concatenated String literals cannot be used to initialize a StaticString. Because its functionality is more restricted than String this means that it is lightweight - only requiring an address pointer and length under the hood. Using StaticString also provides a small performance boost with OS-level memory management because it is neither allocated nor deallocated (no need for reference counting).
Using Apple's recommended Logger API for logging is better than print statements for multiple reasons: performance, privacy and unified management. It can be better for debugging issues in released products (OS Logs provide more context).
I would recommend using StaticString where you can, for example with the function and file names, and UInt for the line and column numbers. This is only now possible with the Logger iOS 14+ API.
(Bonus) Logging Considerations
Should I do LOTS of logging?
I think logging is a balancing act. Lots of logging can be very helpful to debug issues when viewing crash reports if you have access to these. However, you need to balance Privacy, Size of the Compiled Binary and Overwhelming the Logging System.
1. Privacy: Redact sensitive info using "\(message, privacy: .private)" and "\(message, privacy: .public)" with Logger, and DON'T print sensitive information when using NSLog or print statements. I would recommend replacing print statements (for production) with OS Logs when they are for debugging purposes. Or use a preprocessor directive (#if DEBUG) inside the logging service to print only on a Debug scheme..
2. Size of the Compiled Binary: Logging statements are essentially more lines of code. The more code you add, the bigger your binary. This is usually not an issue, as long as you don't log everything under the sun since only a large increase in this metric would affect the binary size.
3. Overwhelming the logging system: If you log excessively, the device may have to discard some logs in order to keep running (limited RAM or swap space at runtime due to OS multitasking - worse for older devices). Apple is usually reliable in handling lots of user logging, and it's hard to achieve this in practice. Nevertheless, if you do encounter this, some more useful log events could be pushed out of the window.
OS Logs
The most important thing to get right is the log level. By default on iOS log entries at .info and below will be suppressed at the point of log generation, so the only real negative with those is the binary size. If you log at .log (.default for os_log) or higher, you need to be careful about not logging too much. Apple's general advice is that you look at each of these higher-level log entries to make sure they contain info that might be useful while debugging.
Finally, make sure to set the subsystem and category. The unified logging system processes a lot of log entries - the subsystem with category makes it much easier for you to focus on specific problems.
How to choose the category and subsystem?
This is a pretty opinionated topic, so I will focus on what I would think about when deciding. YMMV: there may be better options and if so, please let me know.
1. By feature (product-specific): For example, if you are a shopping app, maybe organise the subsystem by the payment, login or other app flows. If you aren't already using a modular codebase for organisation into features (or frameworks for shared code) then I can recommend this tutorial series.
2. By technology: What I mean by this is the domain of the code, is it for Push Notifications, Deep Links, User Defaults (or persistence) logic. This could be helpful for the category parameter.
3. By target: I like to also use the bundleIdentifier of the current Bundle if I can for the subsystem. This makes even more sense if you have Extension Targets (Push Notifications), multiple Targets, or different Platforms (like WatchOS, SiriKit extensions and similar). You can get the current bundle, using this code:
let myBundle = Bundle(for: MyClass.self)
Debugging user issues using OS device logs
See here for a detailed walkthrough (Access Device Console Logs). The main idea is to connect the device to your Mac (or use the Mac itself for Mac apps ;)), open Console.app, run the app and try to reproduce the crash. If you manage to get that far in the first place, then you can correlate the time of the crash with the logs for more context.
Any other reasons for logging less?
If you are an Apple Early-Adopter then you know how buggy some of the iOS Betas can be ;). When posting bug reports to Apple, the OS Logs get included in sysdiagnose files, so you may get a faster turnaround time because your bug reports have less noise.
Should I use a third-party logging service?
Depends if you can afford it and whether you really need it. I prefer to minimise the number of third-party dependencies I import in my code (if I can control this) and the native (Apple) Logging APIs worked fine for most of my use cases. These services charge extra per month, but the advantage is the user cannot view the logs (even if he wants to) by hooking his device up to Console.app on his Mac. Note that this is NOT an issue if you apply the .private log levels, so I don't usually use third-party services (YMMV). A potential reason to go for web-logging is more security against reverse-engineering though, as long as you trust the third-party vendor against data breaches (BUT also it's not as eco-friendly ;)).
static func DLog(message: String, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) {
print("\(file) : \(function) : \(line) : \(column) - \(message)")
}
add where ever you want in your code (inside a struct/var/closure/func...) the next line:
let _ = print("**** \(#file)" + String(describing: type(of: self)) + ".\(#function)[\(#line)]")
and it will print the next line:
**** /path/to/my/file.swift MyClass.someFunc()[17]
Related
Detecting if Mac has a backlit keyboard
It’s quite easy to detect if Mac has an illuminated keyboard with ioreg at the command line: ioreg -c IOResources -d 3 | grep '"KeyboardBacklight" =' | sed 's/^.*= //g' But how can I programmatically get this IOKit boolean property using the latest Swift? I’m looking for some sample code.
I figured out the following with some trial and error: Get the "IOResources" node from the IO registry. Get the "KeyboardBacklight" property from that node. (Conditionally) convert the property value to a boolean. I have tested this on an MacBook Air (with keyboard backlight) and on an iMac (without keyboard backlight), and it produced the correct result in both cases. import Foundation import IOKit func keyboardHasBacklight() -> Bool { let port: mach_port_t if #available(macOS 12.0, *) { port = kIOMainPortDefault // New name as of macOS 12 } else { port = kIOMasterPortDefault // Old name up to macOS 11 } let service = IOServiceGetMatchingService(port, IOServiceMatching(kIOResourcesClass)) guard service != IO_OBJECT_NULL else { // Could not read IO registry node. You have to decide whether // to treat this as a fatal error or not. return false } guard let cfProp = IORegistryEntryCreateCFProperty(service, "KeyboardBacklight" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), let hasBacklight = cfProp as? Bool else { // "KeyboardBacklight" property not present, or not a boolean. // This happens on Macs without keyboard backlight. return false } // Successfully read boolean "KeyboardBacklight" property: return hasBacklight }
As an addendum to Martin’s excellent answer, here are the notes I got from Apple’s Developer Technical Support: Calling I/O Kit from Swift is somewhat challenging. You have two strategies here: You can wrap the I/O Kit API in a Swift-friendly wrapper and then use that to accomplish your task. You can just go straight to your task, resulting in lots of ugly low-level Swift. Pulling random properties out of the I/O Registry is not the best path to long-term binary compatibility. Our general policy here is that we only support properties that have symbolic constants defined in the headers (most notably IOKitKeys.h, but there are a bunch of others). KeyboardBacklight has no symbolic constant and thus isn’t supported. Make sure you code defensively. This property might go away, change meaning, change its type, and so on. Your code must behave reasonable in all such scenarios. Please make sure you file an enhancement request for a proper API to get this info, making sure to include a high-level description of your overall goal.
Why is FileHandle inconsistently returning 'nil'
I have an app which is inconsistently returning 'nil' when using FileHandle to open a file for Read. I'm on OSX (10.13.4), XCode 9.4, Swift 4.1 This OSX app uses the NSOpenPanel() to get a list of files selected by the user. My 'model' class code opens these files to build a collection of data structures The code which does this starts out like this and successfully gets a FileHandle EVERY TIME for any file and is able to read data from the file. private func getFITHeader(filename: String) { let file: FileHandle? = FileHandle(forReadingAtPath: filename) if file == nil { print("FITFile >>> File open failed for file \(filename)") } else { var databuffer: Data databuffer = (file?.readData(ofLength: 80))! : : } The files also contain a block of binary data which I process in another part of the app. While I develop the code for this I'm temporarily hard coding one of the same filenames as works above for test purposes. BUT this code (below) ALWAYS throws an exception 'Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value' when it gets to fileHandle?.seek() - for some reason the attempt to create a FileHandle is always returning 'nil' despite the code being functionally identical to tha above. #IBAction func btnProcFile(_ sender: Any) { var data: Data let filename = "/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit" let fileHandle: FileHandle? = FileHandle(forReadingAtPath: filename) fileHandle?.seek(toFileOffset: 2880) //skip past the headers let dataLenToRead = 1391 * 1039 * 2 data = (fileHandle?.readData(ofLength: dataLenToRead))! : : } The code in the second function works fine in a Playground (not attaching too much meaning to that) and, wierdly, has also worked when temporarily added to a different project. Probably also worth mentioning the length of the file path doesn't seem to matter - it behaves the same on short paths. So the question is - why is this behaviour of FileHandle reliably inconsistent? print()'ing the filenames presented to FileHandle() showed they were identical in each case (see below). So I'm stumped and frustrated by this - any perspectives or workarounds would be appreciated. /Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit /Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit
Found the answer - Sandboxing !! Darren - coincidentally I did look at the URL based route and discovering it 'throws' put some proper error reporting in the catches. Low and behold they reported I didn't have permissions on the file (which initially surprised me since I'm obviously admin on my Mac's and all the files ar local and under my username. I bit more research turned up. this article - https://forums.developer.apple.com/thread/96062 which quickly revealed its a sandboxing problem :-) Looks like recent versions of XCode have it turned on in 'Entitlements'. The post also points out that the NSOpenPanel FileOpen dialog returns 'Security scoped urls'. At first I thought this explained why the code in the first function worked but I'm not totally convinced because I was only feeding the url.path property to FileHandle. However, turning off Sandbox in Entitlements makes everything work just fine. Yes, I know thats not the right thing to do longer term (or if I want this to go to the App Store) so I'll be checking out the right way to do this. At least I can get on now - thanks for the input.
The FileHandle initializers are not well named. You should use FileHandle(forReadingFrom:URL) instead of FileHandle(forReadingAtPath:String). The former is newer API that throws an error instead of returning nil. You can use the thrown error to see why it is failing, and your variables are guaranteed to be non-nil. For example: #IBAction func btnProcFile(_ sender: Any) { do { let fileUrl = URL(fileURLWithPath:"/Users/johncneal/Dropbox/JN Astronomy/Astronomy/Spectroscopy/RSpec_Analyses/Gamma_Cas/20161203/Gamma Cas_065.fit") let fileHandle = try FileHandle(forReadingFrom: fileUrl) fileHandle.seek(toFileOffset: 2880) //skip past the headers let dataLenToRead = 1391 * 1039 * 2 let data: Data = fileHandle.readData(ofLength: dataLenToRead) // etc... } catch let error as NSError { print("FITFile >>> File open failed: \(error)") NSApp.presentError(error) } }
Xcode takes long time to print debug results.
When I debug on Xcode it takes around 30 seconds or more to print results of po on Xcode console. Unfortunately, this is only few information I have on the issue. However, there is another point to consider. This issue is very specific to a project. This is because when I use po for other projects on same Macbook, it works immediately. Also, this particular project is slow on all other Macbook, and for all team. I googled it but no relevant answer found. I find it easy to use print(...) rather than using debugging on Xcode console. However, it's more work and requires lots of rebuilds.
I have several explanations: There is a lot of code (Xcode slows down after a certain amount of code) Also make sure your print statement is towards the top of your page. Xocde goes from top to bottom. Your Mac is slow. Some Macs after a certain amount of usage slow down. Also if you have a Mac mini or air they are slower than others. Xcode Beta. If you are using Xcode beta then there might just be a bug. If none of those answer you provide me with more info and I provide other solutions.
Swift: Try this solution which helps to reduce log time in debug mode. Step 1: Create a new file called Utils.swift (File name based on your preference) Step 2: Add following code in file import Foundation import UIKit struct Utils { } public func PrintLogs(_ message: Any, file: String = #file, function: String = #function, line: Int = #line) { #if DEBUG let className = file.components(separatedBy: "/").last ?? "" let classNameArr = className.components(separatedBy: ".") NSLog("\n\n--> Class Name: \(classNameArr[0]) \n--> Function Name: \(function) \n--> Line: \(line)") print("--> Log Message: \(message)") #endif } Usage: Call PrintLogs("Hello") instead of print("Hello") Sample Output: --> Class Name: HomeViewController --> Function Name: logTest() --> Line: 81 --> Log Message: Hello
Scripting Bridge classes with Swift 3
I am trying to instantiate a SB class using Swift but it doesn't seem to work: if let messageClass = (mail as! SBApplication).class(forScriptingClass:"outgoing message") { let message = (messageClass as! SBObject.Type).init(properties: ["subject": "message subjects"]) as MailOutgoingMessage mail.outgoingMessages!().add(message) print("Subject: \(message.subject)") print("Outgoing messages: \(mail.outgoingMessages!().count)") } All I get in the output is: Subject: nil Outgoing messages: 0 I know that I should cast the message to a MailOutgoingMessage.type and not SBObject.type but I couldn't access the init method otherwise. Someone has experience using Scripting Bridge with Swift? Clues?
Scripting Bridge is nasty, obfuscated and broken. If you have to use SB, Tony Ingraldi wrote some helper tools for Swift users. TBH, I recommend using AppleScript-ObjC over SB simply because AppleScript at least works. For a native Swift-AE bridge, see SwiftAutomation. I'm still working on the documentation, but the code itself descends from appscript which is the only AppleScript alternative of the last 20 years that actually works right, so is just about beta-quality now. Swift (and AppleScript) users who'd like to see Apple adopt SwiftAutomation in 10.3 are strongly encouraged to submit duplicate Radar tickets to bugreport.apple.com requesting it, e.g. here's one already copied to OpenRadar if you want to copy-paste it as-is (include the original rdar:// to help the Radar team resolve it quicker): openradar.appspot.com/29332915
Swift: print() vs println() vs NSLog()
What's the difference between print, NSLog and println and when should I use each? For example, in Python if I wanted to print a dictionary, I'd just print myDict, but now I have 2 other options. How and when should I use each?
A few differences: print vs println: The print function prints messages in the Xcode console when debugging apps. The println is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println, you can now safely replace it with print. Back in Swift 1.x, print did not add newline characters at the end of the printed string, whereas println did. 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 "". NSLog: NSLog adds a timestamp and identifier to the output, whereas print will not; NSLog statements appear in both the device’s console and debugger’s console whereas print only appears in the debugger console. NSLog in iOS 10-13/macOS 10.12-10.x uses printf-style format strings, e.g. NSLog("%0.4f", CGFloat.pi) that will produce: 2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416 NSLog from iOS 14/macOS 11 can use string interpolation. (Then, again, in iOS 14 and macOS 11, we would generally favor Logger over NSLog. See next point.) Nowadays, while NSLog still works, we would generally use “unified logging” (see below) rather than NSLog. Effective iOS 14/macOS 11, we have Logger interface to the “unified logging” system. For an introduction to Logger, see WWDC 2020 Explore logging in Swift. To use Logger, you must import os: import os Like NSLog, unified logging will output messages to both the Xcode debugging console and the device console, too Create a Logger and log a message to it: let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "network") logger.log("url = \(url)") When you observe the app via the external Console app, you can filter on the basis of the subsystem and category. It is very useful to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app, or (b) messages from other categories or types. You can specify different types of logging messages, either .info, .debug, .error, .fault, .critical, .notice, .trace, etc.: logger.error("web service did not respond \(error.localizedDescription)") So, if using the external Console app, you can choose to only see messages of certain categories (e.g. 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. By default, non-numeric data is redacted in the logs. In the example where you logged the URL, if the app were invoked from the device itself and you were watching from your macOS Console app, you would see the following in the macOS Console: url = <private> If you are confident that this message will not include user confidential data and you wanted to see the strings in your macOS console, you would have to do: logger.log("url = \(url, privacy: .public)") Prior to iOS 14/macOS 11, iOS 10/macOS 10.12 introduced os_log for “unified logging”. For an introduction to unified logging in general, see WWDC 2016 video Unified Logging and Activity Tracing. Import os.log: import os.log You should define the subsystem and category: let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network") When using os_log, you would use a printf-style pattern rather than string interpolation: os_log("url = %#", log: log, url.absoluteString) You can specify different types of logging messages, either .info, .debug, .error, .fault (or .default): os_log("web service did not respond", type: .error) You cannot use string interpolation when using os_log. For example with print and Logger you do: logger.log("url = \(url)") But with os_log, you would have to do: os_log("url = %#", url.absoluteString) The os_log enforces the same data privacy, but you specify the public visibility in the printf formatter (e.g. %{public}# rather than %#). E.g., if you wanted to see it from an external device, you'd have to do: os_log("url = %{public}#", url.absoluteString) You can also use the “Points of Interest” log if you want to watch ranges of activities from Instruments: let pointsOfInterest = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest) And start a range with: os_signpost(.begin, log: pointsOfInterest, name: "Network request") And end it with: os_signpost(.end, log: pointsOfInterest, name: "Network request") For more information, see https://stackoverflow.com/a/39416673/1271826. Bottom line, print is sufficient for simple logging with Xcode, but unified logging (whether Logger or os_log) achieves the same thing but offers far greater capabilities. The power of unified logging comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle. So, you frequently will want to test on a physical device, running the app from the device itself, not starting the app from Xcode’s debugger. Unified logging lets you still watch your iOS device log statements from the macOS Console app.
If you're using Swift 2, now you can only use print() to write something to the output. Apple has combined both println() and print() functions into one. Updated to 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:".")
Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)! Don't forget about debugPrint() which works like print() but most suitable for debugging. Examples: Strings print("Hello World!") becomes Hello World debugPrint("Hello World!") becomes "Hello World" (Quotes!) Ranges print(1..<6) becomes 1..<6 debugPrint(1..<6) becomes Range(1..<6) Any class can customize their debug string representation via CustomDebugStringConvertible protocol.
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. From Apple: The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. 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. 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). Then, use Unified Logging (os_log) as much as possible for everything else.
iOS logger NSLog - add meta info (like timestamp and identifier) and allows you to output 1023 symbols. Also print message into Console. The slowest method. Is not safe because other applications has an access to log file #import Foundation NSLog("SomeString") print - prints all string to Xcode. Has better performance than previous #import Foundation print("SomeString") println (only available Swift v1) and add \n at the end of string os_log (from iOS v10) - prints 32768 symbols also prints to console. Has better performance than previous #import os.log os_log("SomeIntro: %#", log: .default, type: .info, "someString") Logger (from iOS v14) - prints 32768 symbols also prints to console. Has better performance than previous #import os let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "someCategory") logger.log("\(s)")
There's another method called dump() which can also be used for logging: 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