How to print() to Xcode console in SwiftUI?

后端 未结 9 1905
刺人心
刺人心 2020-12-14 00:24

So I tried to put a print statement while debugging in a SwiftUI View.

print(\"landmark: \\(landmark)\")

In the following body.

<         


        
相关标签:
9条回答
  • 2020-12-14 01:06

    It can be generalized to:

    extension View {
        func Perform(_ block: () -> Void) -> some View {
            block()
            return EmptyView()
        }
    }
    

    So in your example:

    ForEach(landmarkData) { landmark in
        Perform { print("landmark: \(landmark)") }
        if !self.userData.showFavoritesOnly || landmark.isFavorite {
            NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
                LandmarkRow(landmark: landmark)
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 01:08

    You can print in the body structure but to do so you have to explcitly return the view you want to render. Normally in SwiftUI, the body property implicitly returns the view. For example, this will throw an error when you try to print:

    struct SomeView: View {
      @State var isOpen = false
    
      var body: some View {
        print(isOpen) // error thrown here
    
        VStack {
          // other view code
        |
      }
    }
    

    But if we explicitly return the view we want then it will work e.g.

    struct SomeView: View {
      @State var isOpen = false
    
      var body: some View {
        print(isOpen) // this ok because we explicitly returned the view below
    
         // Notice the added 'return' below
         return VStack {
          // other view code
        }
      }
    }
    

    The above will work well if you're looking to view how state or environment objects are changing before returning your view, but if you want to print something deeper down within the view you are trying to return, then I would go with @Rok Krulec answer.

    0 讨论(0)
  • 2020-12-14 01:09

    Very easy way to debug your Preview:

    1. Open your Swift project in Xcode 11.
    2. Right-click (or Control-click) on the Live Preview button in the bottom right corner of the preview.
    3. Select Debug Preview.

    How to debug your SwiftUI previews in Xcode

    0 讨论(0)
提交回复
热议问题