Quick tip – logging within SwiftUI

SwiftUI doesn’t allow the adding of a surreptitious print statement within a SwiftUI view, to aid debugging. I recently had an issue where I was initializing Core Data properties within a view model initializer, and the code was being called repeatedly in a loop. I really needed to get to the bottom of why, but it was proving difficult to do so, without being able to drop some print statements at various places in the UI code to better understand what was going on.

While its not possible to add print statements in SwiftUI, it is possible to call functions from SwiftUI (that return Views), and those functions obviously contain normal Swift code, which can include print statements. So this solution worked. Heres a function that returns an EmptyView, and also prints something :

func log(_ log: String) -> EmptyView {
    print("** \(log)")
    return EmptyView()
}

I can then drop that EmptyView anywhere within a SwiftUI view hierarchy, for example right next to a view that I am  interested in the lifecycle of, and it doesn’t affect the view, because its empty:

var body: some View {
        VStack {
            log("MainListView: VStack")
            HStack {

Thats it – a quick way to add logging within SwiftUI code.  Its interesting to see whats going on under the hood and the results are often really not expected.

6 thoughts on “Quick tip – logging within SwiftUI”

    1. Hi Jim, thats what Im doing – printing then returning a View. I know this might have been obvious to some already but it only occurred to me yesterday! Its really interesting to see just how often SwiftUI is running your View code – really often it turns out.

  1. 1149 — Throw laptop against wall. Share SwiftUI observations with recalcitrant device.
    1151 — Read about ‘log’ from another, undamaged, computer.
    1153 — Pick up laptop from floor. Inject ‘log’ there, and there, and especially THERE.
    1154 — Stare quizzically at non-output.
    1155 — Same
    1156 — Same
    1157 — Look elsewhere.
    1158 — Fix problem.

    1. Hi David, did the above not work for you? Its defo work in latest XCode etc and I previously had no other way of printing from within a SwiftUI view definition.

Leave a Reply

Your email address will not be published. Required fields are marked *