In Daily Coding Tip 217 I showed how you can use View._printChanges()
to print a message in the console whenever the view refreshes.
This is an undocumented function that always does what Apple created it for: it tells you what property change occurred that resulted in the view being refreshed. There is no option to print any other information, such as what the value of the property that changed (or any other property).
The fact that the View._printChanges()
function is undocumented also means that your App Store submission will be rejected from if you use it.
Instead of using that I’m creating my own function that can be put anywhere in the View body
, and I can write whatever code I want to run when the view is refreshed there. The function doesn’t return anything, but in Swift every function that doesn’t return anything actually returns Void
.
This is important because it explains how I can use it in the following assignment:
let _ = printRefresh()
It is now thankfully possible to create local variables inside the body
. If I had simply put printRefresh()
into the body
, I would have got the following error:
Type '()' cannot conform to 'View'
In this case ()
is equivalent to Void
, the return type of printRefresh()
and every other function in Swift that appears to return nothing. By assigning it to the underscore _
I am effectively throwing that function result away and not storing it anywhere, whilst giving myself the ability to run the function that created it.
This is the same way that the View._printChanges()
function was called in Daily Coding Tip 217.
You might be wondering what’s going on with viewHasAppeared
.
I originally had my function printing “view was refreshed” even when the view was created for the first time, which doesn’t really seem like a refresh to me. To get around this I make it clear when the view has been created for the first time, which happens before the .onAppear
modifier changes viewHasAppeared
to true
.