Using Guided Generation in Foundation Models
- lioneldude
- Jul 17
- 2 min read
In the Foundation Models framework unveiled at WWDC25, the generated response is of the String type. If you wish to create Swift Data structures, the framework supports guided generation, enabling the response to be output in the form of your predefined structure.
First we create a struct of the type that we wish to generate. Let's create a type of Superhero, defined as:

TThe whole struct is defined using a macro called @Generable, with a description provided as a string to assist with guided generation. We specify the attributes of the Superhero, including name, age, and even an array of interests and powers. Each attribute can be annotated with @Guide to offer additional details. For instance, the hero possesses 2 to 6 interests and 1 power.
Rather than placing the request directly within the project's View, let's develop an Observable class named SuperheroGenerator. This class will incorporate the Language Model Session. It contains the Superhero, but because we are streaming the response, we classify it as PartiallyGenerated.

We start by initializing the class with instructions of the String type. The function responsible for generating the hero will include the logic, consisting of just three lines of code. We assign the stream to invoke the function .streamResponse(to:generating:), and within the for loop, we assign self.superhero to partialResponse. Since this function is asynchronous and may throw errors, we need to use try await.

In the SwiftUI view, we set up a button to initiate the logic that utilizes the function from the SuperheroGenerator class. The observable class property, superhero, is a published property that we focus on. As soon as the model provides part of its response, we can present it in our SwiftUI view. For the complete code, visit my GitHub link at:

Comments