lukecsmith.co.uk

Quick tip – logging within SwiftUI

Luke, 27 May 2020

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.

Tagged with: