Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print() to Xcode console in SwiftUI?

Tags:

swiftui

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

print("landmark: \(landmark)")

In the following body.

var body: some View {
    NavigationView {
        List {
            Toggle(isOn: $userData.showFavoritesOnly) {
                Text("Favorite only")
            }
            ForEach(landmarkData) { landmark in
                print("landmark: \(landmark)")
                if !self.userData.showFavoritesOnly || landmark.isFavorite {
                    NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
                        LandmarkRow(landmark: landmark)
                    }
                }
            }
        }
       .navigationBarTitle(Text("Landmarks"))            
    }
}

Compiler errors out: Xcode compiler error

So, what is the proper way to print to console in SwiftUI?

EDIT: I made Landmark conform to CustomStringConvertible:

struct Landmark: Hashable, Codable, Identifiable, CustomStringConvertible {

var description: String { name+"\(id)" }

var id: Int
var name: String
.....

I still get the "String is not convertible to any" error. Should it work now?

like image 250
zumzum Avatar asked Jun 09 '19 19:06

zumzum


People also ask

How do I display print in Xcode?

Press ⇧⌘Y or choose View > Debug Area > Show Debug Area to show the console output (or ⇧⌘C / Activate Console). Usually, this window will open automatically when your program produces output (this is controlled by the Behaviors section of Xcode's Preferences).

How do I print a SwiftUI view?

Use print statement inside SwiftUI view You need to assign print() to a variable ( var ) or a constant ( let ). Here is an example of how we can use print() in a SwiftUI view. Text("Hello, World!") 1 and 2 We don't use the returning result ( x and y ) anywhere.

How do you print a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.


2 Answers

At least in Xcode 12/Swift 5.3, you can easily add a print statement anywhere in a function builder by simply storing its return value in a wildcard, effectively ignoring it:

let _ = print("hi!") 

No setup or other verbosity needed!

like image 52
juliand665 Avatar answered Sep 19 '22 10:09

juliand665


Here's a helper Print( ... ) View that acts like a print( ... ) function but within a View

Put this in any of your view files

extension View {
    func Print(_ vars: Any...) -> some View {
        for v in vars { print(v) }
        return EmptyView()
    }
}

and use inside of body like so

Print("Here I am", varOne, varTwo ...)

or inside a ForEach {} like so

self.Print("Inside ForEach", varOne, varTwo ...)

Note: you might need to put Print() into a Group {} when combining with existing views

like image 25
Rok Krulec Avatar answered Sep 19 '22 10:09

Rok Krulec