14.4 C
Canberra
Tuesday, July 22, 2025

Working with @Generable and @Information in Basis Fashions


Within the earlier tutorial, we launched the Basis Fashions framework and demonstrated easy methods to use it for primary content material technology. That course of was pretty simple — you present a immediate, wait a number of seconds, and obtain a response in pure language. In our instance, we constructed a easy Q&A app the place customers may ask any query, and the app displayed the generated textual content immediately.

However what if the response is extra advanced — and you have to convert the unstructured textual content right into a structured object?

For instance, suppose you ask the mannequin to generate a recipe, and also you need to flip that response right into a Recipe object with properties like identifyelements, and directions.

Do you have to manually parse the textual content and map every half to your information mannequin?

The Basis Fashions framework in iOS 26 offers two highly effective new macros known as Generable and @Information to assist builders simplify this course of.

On this tutorial, we’ll discover how these macros work and the way you should utilize them to generate structured information immediately from mannequin output.

The Demo App

generable-macro-demo-app.png

We are going to construct a easy Quiz app that demonstrates easy methods to use Basis Fashions to generate structured content material. On this case, it’s the vocabulary questions for English learners.

The app shows a multiple-choice query with 4 reply choices, permitting customers to check their data interactively. Every query is generated by the on-device language mannequin and robotically parsed right into a Swift struct utilizing the @Generable macro.

This demo app reveals how builders can transfer past primary textual content technology and use Basis Fashions to create structured content material.

Utilizing @Generable and @Information

Let’s get began with constructing the demo app. As mentioned earlier than, in contrast to the earlier Q&A demo, this quiz app presents a multiple-choice query with a number of reply choices. To symbolize the query, we’ll outline the next construction in Swift:

struct Query {
    let textual content: String
    let decisions: [String]
    let reply: String
    let rationalization: String
}

Later, we’ll ask the on-device language mannequin to generate quiz questions. The problem is how we will convert the mannequin’s unstructured textual content response right into a usable Query object. Thankfully, the Basis Fashions framework introduces the @Generable macro to simplify the conversion course of.

To allow automated conversion, merely mark your struct with @Generable, like this:

import FoundationModels

@Generable
struct Query {
    @Information(description: "The quiz query")
    let textual content: String
    @Information(.depend(4))
    let decisions: [String]
    let reply: String
    @Information(description: "A short rationalization of why the reply is appropriate.")
    let rationalization: String
}

The framework additionally introduces the @Information macro, which permits builders to offer particular directions to the language mannequin when producing properties. As an example, to specify that every query ought to have precisely 4 decisions, you should utilize @Information(.depend(4)) on the decisions array property.

With array, apart from controlling the precise variety of ingredient, you may also use the next guides:

.minimumCount(3)
.maximumCount(100)

You may as well add a descriptive rationalization to a property to provide the language mannequin extra context concerning the sort of information it ought to generate. This helps make sure the output is extra correct and aligned along with your expectations.

It’s essential to concentrate to the order wherein properties are declared. When utilizing a Generable kind, the language mannequin generates values sequentially based mostly on the order of the properties in your code. This turns into particularly essential when one property’s worth depends on one other. For instance, within the code above, the rationalization property is determined by the reply, so it needs to be declared after the reply to make sure it references the proper context.

Constructing the Quiz App

With the Query construction prepared, we dive into the implementation of the Quiz app. Swap again to ContentView and replace the code like this:

import FoundationModels

struct ContentView: View {
    
    @State personal var session = LanguageModelSession(directions: "You're a highschool English instructor.")
    
    @State personal var query: Query?
    
    var physique: some View {
        VStack(spacing: 20) {
            
            if let query {
                QuestionView(query: query)
            } else {
                ProgressView("Producing questions ...")
            }
            
            Spacer()
            
            Button("Subsequent Query") {
                Process {
                    do {
                        query = nil
                        query = strive await generateQuestion()
                    } catch {
                        print(error)
                    }
                }
            }
            .padding()
            .body(maxWidth: .infinity)
            .background(Colour.inexperienced.opacity(0.18))
            .foregroundStyle(.inexperienced)
            .font(.headline)
            .cornerRadius(10)

        }
        .padding(.horizontal)
        .activity {
            do {
                query = strive await generateQuestion()
            } catch {
                print(error)
            }
        }
    }
    
    func generateQuestion() async throws -> Query {
        
        let response = strive await session.reply(to: "Create a vocabulary quiz for highschool college students. Generate one multiple-choice query that exams vocabulary data.", producing: Query.self)
        
        return response.content material
    }
}

The person interface code for this app is straightforward and straightforward to observe. What’s price highlighting, nevertheless, is how we combine the Basis Fashions framework to generate quiz questions. Within the instance above, we create a LanguageModelSession and supply it with a transparent instruction, asking the language mannequin to tackle the function of an English instructor.

To generate a query, we use the session’s reply methodology and specify the anticipated response kind utilizing the producingparameter. The session then robotically produces a response and maps the end result right into a Query object, saving you from having to parse and construction the info manually.

Subsequent, we’ll implement the QuestionView, which is chargeable for displaying the generated quiz query, dealing with person interplay, and verifying the chosen reply. Add the next view definition inside your ContentView file:

struct QuestionView: View {
    let query: Query
    
    @State personal var selectedAnswer: String? = nil
    @State personal var didAnswer: Bool = false

    var physique: some View {
        ScrollView {
            VStack(alignment: .main) {
                Textual content(query.textual content)
                    .font(.title)
                    .fontWeight(.semibold)
                    .padding(.vertical)
                
                VStack(spacing: 12) {
                    ForEach(query.decisions, id: .self) { alternative in
                        
                        Button {
                            if !didAnswer {
                                selectedAnswer = alternative
                                didAnswer = true
                            }

                        } label: {
                            if !didAnswer {
                                Textual content(alternative)
                            } else {
                                HStack {
                                    if alternative == query.reply {
                                        Textual content("✅")
                                    } else if selectedAnswer == alternative {
                                        Textual content("❌")
                                    }
                                    
                                    Textual content(alternative)
                                }
                            }
                        }
                        .disabled(didAnswer)
                        .padding()
                        .body(maxWidth: .infinity)
                        .background(
                            Colour.blue.opacity(0.15)
                        )
                        .foregroundStyle(.blue)
                        .font(.title3)
                        .cornerRadius(12)

                    }
                }
                
                if didAnswer {
                    
                    VStack(alignment: .main, spacing: 10) {
                        Textual content("The proper reply is (query.reply)")
                        
                        Textual content(query.rationalization)
                    }
                    .font(.title3)
                    .padding(.prime)
                }
            }
            

        }
    }
    
}

This view presents the query textual content on the prime, adopted by 4 reply decisions rendered as tappable buttons. When the person selects a solution, the view checks if it’s appropriate and shows visible suggestions utilizing emojis (✅ or ❌). As soon as answered, the proper reply and an evidence are proven beneath. The @State properties observe the chosen reply and whether or not the query has been answered, permitting the UI to replace reactively.

As soon as you’ve got carried out all the mandatory adjustments, you may check the app within the Preview canvas. You need to see a generated vocabulary query just like the one proven beneath, full with 4 reply decisions. After choosing a solution, the app offers fast visible suggestions and an evidence.

generable-macro-demo-test.png

Abstract

On this tutorial, we explored easy methods to use the Basis Fashions framework in iOS 26 to generate structured content material with Swift. By constructing a easy vocabulary quiz app, we demonstrated how the brand new @Generable and @Information macros can flip unstructured language mannequin responses into typed Swift structs.

Keep tuned — within the subsequent tutorial, we’ll dive into one other highly effective function of the Basis Fashions framework.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles