Syntax on page 33 example(of: )

There is this syntax I’ve never encountered before on page 33

example(of: “creating and linking nodes”)

Can someone tell me what is going on in this syntax or provide a link to a reference?

The example function is a custom function of ours. You can find the definition in sources. It takes a string and a closure and then just prints out the string and runs the closure. This is great because each example can have its own scope and when you go look at the console output you can tell what output corresponds to what example.

1 Like

Hello, i am a beginner in swiftui and I’ve just purchased this book.
as of now im stuck on example(of: “creating and linking nodes”), can you provide more details
on how this function is working. because it keeps giving me a error " cannot find example in scope.

thank you

1 Like

Hi. Thanks for the question. In playgrounds extra code can be put in the “Sources” directory. If you don’t see the navigation sidebar in Xcode, you can hit Command-0 to see it. For the Stacks chapter, it is stored under Helpers.swift and has this definition:

public func example(of description: String, action: () -> ()) {
  print("---Example of \(description)---")

The reason for using this is so that each example has it’s own lexical scope allowing you to use the same nice variable names such as node and stack in each example.

Hope that helps.

Maybe I should also mention that there is a “starter playground” for the different exercises and examples. These put in the minimal (boring stuff) so that you can follow along with the main subject and not start from zero every time. If you are following along and doing the challenges, I recommend starting with these starters projects rather than a blank playground. You can always inspect what is there using the command-0.

Thanks for the response.
I understand now that it’s a custom function.