Friday, September 12, 2025
HomeiOS DevelopmentLogging for newbies in Swift

Logging for newbies in Swift


Primary output in Swift utilizing print

The very first technique I would like to indicate you is the print perform. It may well write the textual illustration of the given objects to the usual output. In different phrases we will merely say that it may print textual content to the display screen. A lot of the howdy phrase packages make the most of this technique to show the well-known “Howdy world!” message. In Swift, print is kind of a strong technique, since you may go round a number of objects for printing out plus you may specify a separator string and a terminator parameter. 🤔

print("Howdy World!")

The snippet above will show the Howdy World! textual content adopted by a newline character (n), it’s because the default terminator is all the time a newline. You may override this habits by offering your individual terminator string.

print("Howdy World!", terminator: "")

Should you run this instance utilizing Xcode you need to see that the “Program ended with exit code: 0” textual content will seem in a newline within the first case, however within the second state of affairs it’s going to be printed out proper after the “Howdy World!” sentence. Should you run this system utilizing a Terminal software, a % character be current as a substitute of the brand new line within the second case. 💡

What about printing out a number of variables? It’s doable to present a number of objects to the print perform, they are often actually something, print can deal with strings, integers and all types of different variables. Print beneath the hood will convert the variable into a correct string illustration, so you do not have to fiddle with sort casting on a regular basis, however merely print out something.

print(1, 2, 3, 4, 5)


print(1, "two", 3.14, true)

You may as well customise the separator character by means of an argument. So should you want a coma character (adopted by an area) in between the weather, you may write one thing like this:

print("a", "b", "c", separator: ", ")

Properly, in my earlier article you’ve gotten seen methods to assemble varied strings utilizing literals and interpolation, you need to use all these variables to print out stuff to the console.

print("""
            __
           / _)
    .-^^^-/ /
 __/       /
<__.|_|-|_|
""")

For instance, here is a cute multi-line ascii artwork dinosaur. 🦕

Debugging and print

Generally it could be cool to know just a bit bit of additional information in regards to the printed variable, that is when debugPrint may help you. The principle distinction between print and debugPrint is that whereas print merely converts every part to string, debug print will provide you with a short debug information in regards to the given objects. The debugPrint technique will print out numbers similar to print does, it’s going to add double quotes round strings, and it will print some additional information about a lot of the different “advanced” varieties.

print(1) 
debugPrint(1) 

print("foo") 
debugPrint("foo") 

print(1...5) 
debugPrint(1...5) 

Truthfully I’ve virtually by no means used this technique, and I all the time most popular print if I needed to print out one thing to the console, nevertheless it’s all the time good to know that there’s such an possibility out there built-in to the usual library, nonetheless there’s a technique that may give you far more information… 🧐

Debugging utilizing dump

The dump technique can print out the given object’s content material utilizing its mirror to the usual output. Lengthy story brief, this perform will present you a extra detailed view in regards to the property. For scalar values the dump technique will produce virtually the identical output as debug-print, besides the dump line all the time begins with a splash character, however for extra advanced varieties it’s going to output the underlying construction of the article. Don’t be concerned, you needn’t perceive the output of this technique, simply keep in mind that it may present you useful information throughout debugging. 🐞

dump(1)
dump(3.14)
dump("foo")
dump(1...5)

The ClosedRange struct is a built-in sort with a lowerBound and an upperBound property. Whereas the print perform solely returned the outlined vary (1…5), the debugPrint technique additionally revealed the kind of the article, dump takes this one step additional by displaying us the precise decrease and higher certain properties of the worth. This may be extraordinarily useful when you’ve gotten a posh sort with plenty of underlying properties that you simply wish to shortly examine for some cause. 🔍

By the best way, debugging is the act of discovering (and resolving) bugs. Bugs are issues in your program code that stop regular operation. Builders can use debugger instruments to run and examine code step-by-step, line by line or per instruction, however most of them are merely placing print statements into the code to see the present state or results of a given perform. 🤷‍♂️

Dump has just a few extra perform arguments which you could configure:

dump("check", identify: "my-variable", indent: 4, maxDepth: 5, maxItems: 5)

You may give a reputation to every dumped variable, add some additional indentation earlier than the sprint character, specify the utmost depth for descendents and the utmost variety of components for which to jot down the total contents. Be at liberty to play with these parameters for some time. 😉

As you may see dump is kind of a strong technique, however nonetheless there are different capabilities for logging functions, let me present you one that’s coming from the Goal-C instances.

NSLog – the legacy logger perform

When you’ve got ever labored with Goal-C you have to be acquainted with the NS prefixes. The NSLog perform can log an error message to the Apple System Log facility console. It isn’t a part of the Swift commonplace library, however you must import the Basis framework so as to use NSLog.

import Basis

NSLog("I am a dinosaur.")

It is best to know that NSLog will print the present date & time first, then it’s going to show the identify of the operating program with the method and thread identifiers and solely then it’s going to print your message.

Simply to be clear, NSLog is coming from the Goal-C period, it isn’t a really helpful logging resolution anymore. It is usually very sluggish and that may trigger some points should you want exactly timed outputs. That is why I do NOT suggest utilizing NSLog in any respect, however you additionally should know that till just a few years in the past there was no higher built-in different for it, I am not judging, simply saying… 😅

Unified Logging and Exercise Tracing

If you wish to ship log messages on an Apple gadget to the unified logging system, you need to use the OSLog framework. This new instrument was launched at WWDC 2016 and lately bought some good API refinements & updates. It is best to undoubtedly examine the OSLog and Unified Logging really helpful by Apple article if you wish to be taught extra about this subject it is an incredible write up.

My solely concern about this logging API is that it isn’t that common. It really works nice on Apple platforms, however since Swift is an common language if you wish to add Linux and even Home windows help, this resolution will not give you the results you want…

SwiftLog – A Logging API package deal for Swift

This open supply package deal could be simply built-in into your Swift tasks by way of the Swift Package deal Supervisor. You simply should set it up as a dependency within the Package deal.swift manifest file or you may hook it utilizing Xcode beneath the File > Swift Packages menu as an SPM dependency.


import PackageDescription

let package deal = Package deal(
    identify: "myProject",
    dependencies: [
        .package(url: "https://github.com/apple/swift-log.git", from: "1.4.0"),
    ],
    targets: [
        .target(name: "myProject", dependencies: [
            .product(name: "Logging", package: "swift-log")
        ])
    ]
)

The utilization is absolutely easy. First you must import the Logging framework, then you definately create a logger and you utilize that logger occasion to print out varied log messages.

import Logging

let logger = Logger(label: "app-identifier")

logger.information("Howdy World!")

The next log ranges are supported:

  • hint
  • debug
  • information
  • discover
  • warning
  • error
  • vital

You may as well connect extra logging metadata to the logger, you need to examine the readme for more information about this feature. SwiftLog is utilized in many real-world tasks, akin to Vapor 4 (a server facet Swift framework), this additionally implies that it really works nice on Linux working techniques. 🐧

Conclusion

If it involves logging, there are a number of good choices to select from. It solely relies on your wants which one is one of the best, however normally we will say that it’s time to depart behind NSLog, and time to make use of the brand new OSLog framework. In case you are utilizing Swift on non-Apple platform you need to think about using the SwiftLog library, which can be offered by Apple.

Alternatively in case you are simply scratching the floor and you do not want that many choices or log ranges you may merely follow print and dump statements. It is completely nice to debug utilizing these easy strategies at first. Mastering one thing takes time and debuggers could be fairly horrifying at first sight. Use print as a lot as you want, however all the time attempt to enhance your instruments & information over time, I hope this text offers you a greater view of the out there logging instruments. 🤓

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments