SwiftUI tiny bits: Little view extension to log to the console

I wanted to log to the console in the middle of a SwiftUI chain but you can’t put “print” statements in SwiftUI code in most places (“Everything must be a View!” ;)). Since I was in a playground I couldn’t set a breakpoint that logged to the console (my standard strategy when in an application context). So I wrote this little thing:

extension View {
  func printMessage(_ msg: Any...,
              separator: String = " ",
              terminator: String = "\n")
            -> some View {
    // Print them out as if not
    // converted to an array.
    for m in msg {
      print(m,
            separator,
            terminator: "")
    }
    print()
    return self
  }
}

Use it like so:

import Cocoa
import PlaygroundSupport
import SwiftUI

extension View {
  func printMessage(_ msg: Any...,
        separator: String = " ",
        terminator: String = "\n")
      -> some View {
  // Print them out as if not
  // converted to an array.
  for m in msg {
    print(m,
      separator,
      terminator: "")
  }
  print()
  return self
  }
}

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Hello")
      Text("World!")
        .padding()
        .background(
          GeometryReader { proxy in
            Color.clear
              .printMessage("Info: ", proxy.size)
        })
    }.padding()
  }
}


struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

PlaygroundPage.current.liveView = NSHostingView(rootView: ContentView())

Output is:

Info:   (72.0, 48.0)
Info:   (72.0, 48.0)  
Info:   (72.0, 48.0)  

Could well be a better way or issues with this, but it’s just something I put together quickly to solve a problem (“what is the value of proxy.size?”) and it seems to work, so thought I’d share it. Improvements or better ways to get the same capabilities are welcome 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s