### Purchase Product Example Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/09-store-integration.md Example of how to initiate a product purchase using the StoreActor. Handles success by updating the UI and errors by displaying a message. ```swift // Purchase a product let actor = StoreActor() do { let result = try await actor.purchase(productID: "com.example.premium_monthly") // Update UI with success } catch { // Show error message } ``` -------------------------------- ### Check Subscription Status Example Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/09-store-integration.md Example of how to check a user's subscription status using the StoreActor. ```swift // Check subscription status let isSubscribed = await actor.isSubscribed(to: "com.example.premium_monthly") ``` -------------------------------- ### Listen to Transaction Updates Example Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/09-store-integration.md Example of how to listen for transaction updates from the SKPaymentQueue. This is crucial for handling new transactions as they occur. ```swift // Listen to transaction updates for await result in SKPaymentQueue.default().transactionUpdates { // Handle new transaction } ``` -------------------------------- ### Usage Example for City Model Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Demonstrates how to retrieve a city by its ID and iterate through its parking spots to print their names. Ensure the cityID is valid to avoid runtime errors. ```swift let city = City.identified(by: cityID) for spot in city.parkingSpots { print("\(city.name): \(spot.name)") } ``` -------------------------------- ### FoodTruckModel Usage Example Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Demonstrates how to instantiate and use the `FoodTruckModel` in SwiftUI, including accessing published properties, creating bindings for editing, fetching data, and sorting donuts. ```swift @StateObject private var model = FoodTruckModel() // Access published properties ForEach(model.orders) { order in OrderRow(order: order) } // Bind to a specific order for editing let binding = model.orderBinding(for: orderId) OrderDetailView(order: binding) // Get top donuts by popularity let topDonuts = model.donuts(sortedBy: .popularity(.month)).prefix(5) // Fetch historical trends let dailySummaries = model.dailyOrderSummaries(cityID: city.id) ``` -------------------------------- ### NavigationStack Integration Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/10-swiftui-components.md Illustrates integrating NavigationLink and .navigationDestination with NavigationStack for hierarchical navigation. This setup allows navigation to OrderDetailView when an Order is selected. ```swift NavigationLink(value: Order.someOrder) { OrderRow(order: someOrder) } .navigationDestination(for: Order.self) { order in OrderDetailView(order: $model.orderBinding(for: order.id)) } ``` -------------------------------- ### Create and Use a Custom Donut Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Demonstrates how to initialize a custom Donut object and access its aggregated flavor profile and search functionality. ```swift let donut = Donut( id: 100, name: "Custom Delight", dough: .chocolate, glaze: .strawberry, topping: .sprinkles ) // Aggregate flavors let profile = donut.flavors // FlavorProfile with summed component flavors print(profile.sweet) // Combined sweetness from dough + glaze + topping // Search if donut.matches(searchText: "choco") { // Matches name or ingredient names containing "choco" } ``` -------------------------------- ### Configure Dynamic Island for Order Details Source: https://github.com/apple/sample-food-truck/blob/main/README.md Sets up the UI for the Dynamic Island to show order preparation status. This includes expanded, compact, and minimal presentations. Ensure WidgetKit is imported. ```swift DynamicIsland { DynamicIslandExpandedRegion(.leading) { ExpandedLeadingView() } DynamicIslandExpandedRegion(.trailing, priority: 1) { ExpandedTrailingView(orderNumber: context.attributes.orderID, timerInterval: context.state.timerRange) .dynamicIsland(verticalPlacement: .belowIfTooWide) } } compactLeading: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape()) } compactTrailing: { Text(timerInterval: context.state.timerRange, countsDown: true) .monospacedDigit() .foregroundColor(Color("LightIndigo")) .frame(width: 40) } minimal: { Image("IslandCompactIcon") .padding(4) .background(.indigo.gradient, in: ContainerRelativeShape()) } .contentMargins(.trailing, 32, for: .expanded) .contentMargins([.leading, .top, .bottom], 6, for: .compactLeading) .contentMargins(.all, 6, for: .minimal) .widgetURL(URL(string: "foodtruck://order/\(context.attributes.orderID)")) ``` -------------------------------- ### Creating a ParkingSpot Instance Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Shows how to initialize a ParkingSpot object with a name, CLLocation, and camera distance. This is useful for defining new parking locations. ```swift let spot = ParkingSpot( name: "Main Street Park", location: CLLocation(latitude: 37.3348, longitude: -122.0090), cameraDistance: 1100 ) ``` -------------------------------- ### Linear Interpolation Between Two Values Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/06-layouts-utilities.md Performs linear interpolation between a starting value and a destination value based on a percentage. A percent of 0 returns the starting value, and 1 returns the destination. The `clamped` parameter restricts the percentage to the 0-1 range. ```swift let start = 0.0 let end = 100.0 let mid = start.interpolate(to: end, percent: 0.5) // 50.0 ``` -------------------------------- ### Create and Update Order Status Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Demonstrates how to initialize an Order object and transition its status using the `markAsNextStep` method. Also shows how to check the `isPreparing` computed property. ```swift var order = Order( id: "Order#001234", status: .placed, donuts: [donut1, donut2], sales: [1: 2, 3: 1], grandTotal: 15.89, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) // Transition order status order.markAsNextStep { newStatus in print("Order is now: \(newStatus.title)") } // Check readiness if order.isPreparing { startCountdown() } ``` -------------------------------- ### Get Most Potent Flavor from Profile Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Returns a tuple containing the most intense flavor type and its intensity value from a FlavorProfile. Used to identify and display the dominant flavor. ```swift let profile = donut.flavors let (flavor, intensity) = profile.mostPotent print("Most potent: \(flavor.name) at \(intensity)") ``` -------------------------------- ### Sign In with Passkey or Password Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Initiates the sign-in process for a user, supporting both passkey and password authentication. Ensure the presentation context is set up before initiating sign-in. ```swift @StateObject private var accountStore = AccountStore() // Set up presentation context (required) accountStore.presentationContextProvider = self // Initiate sign-in let controller = ASAuthorizationController(authorizationRequests: [...]) await accountStore.signIntoPasskeyAccount(authorizationController: controller) // Check result if accountStore.isSignedIn { if case .authenticated(let username) = accountStore.currentUser { print("Welcome, \(username)") } } ``` -------------------------------- ### easeInOut(clamped:) Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Applies an ease-in/ease-out timing function to a value, typically used for smoothing animation progress. It creates a natural curve by slowing down the start and end of the animation. ```APIDOC ## easeInOut(clamped:) ### Description Applies ease-in/ease-out timing to an animation progress value. This creates a smoother, more natural animation curve by slowing down the start and end. ### Method `func easeInOut(clamped: Bool = true) -> Self` ### Parameters * `clamped` (Bool) - Optional - If true, clamps the input value to the range of 0 to 1. ### Returns Eased value between 0 and 1. ### Usage Smooths linear animation progress into a more natural curve. ### Example ```swift for step in stride(from: 0.0, through: 1.0, by: 0.1) { let eased = step.easeInOut() print("Progress: \(step), Eased: \(eased)") } ``` ``` -------------------------------- ### Generate Sample Orders with OrderGenerator Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md Demonstrates how to generate today's orders, historical data, and reproducible orders using the OrderGenerator class. It shows how to use a seeded random number generator for deterministic results. ```swift struct OrderGeneratorExample { let generator = OrderGenerator(knownDonuts: Donut.all) // Generate today's orders func loadTodayOrders() -> [Order] { generator.todaysOrders() } // Generate historical data func loadHistoricalData() { let dailySummaries = generator.historicalDailyOrders( since: .now, cityID: City.cupertino.id ) print("60 days of data: \(dailySummaries.count) summaries") let monthlySummaries = generator.historicalMonthlyOrders( since: .now, cityID: City.sanFrancisco.id ) print("12 months of data: \(monthlySummaries.count) summaries") } // Generate with deterministic randomness func generateReproducibleOrders() -> [Order] { var rng = OrderGenerator.SeededRandomGenerator(seed: 42) var orders: [Order] = [] for i in 0..<10 { let order = generator.generateOrder( number: i + 1, date: Date(timeIntervalSinceNow: TimeInterval(-i * 600)), generator: &rng ) orders.append(order) } return orders } } ``` -------------------------------- ### Aggregate Sales Data by Timeframe Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/07-enums-constants.md The Timeframe enum defines windows for sales data aggregation. Examples demonstrate fetching monthly sales summaries, calculating weekly sales, and iterating through all available timeframes. ```swift // Monthly sales chart let summaries = model.orderSummaries(for: city.id, timeframe: .month) // Get aggregate sales for this week let weeklySales = model.combinedOrderSummary(timeframe: .week) print("This week: \(weeklySales.totalSales) donuts sold") // Loop over all timeframes for timeframe in Timeframe.allCases { let sales = model.donutSales(timeframe: timeframe) } ``` -------------------------------- ### Iterating and Accessing Flavor Cases Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/07-enums-constants.md Demonstrates how to iterate through all available flavor cases and access specific flavor properties like name and image. Also shows how to retrieve a specific flavor from a profile. ```swift for flavor in Flavor.allCases { print(flavor.name) // "Salty", "Sweet", etc. let icon = flavor.image } let profile = donut.flavors let spiciness = profile[.spicy] ``` -------------------------------- ### Sort Donuts by Popularity, Name, or Flavor Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/07-enums-constants.md Use the DonutSortOrder enum to specify sorting criteria for donut catalogs. Examples show sorting by popularity within a timeframe, alphabetically by name, or by flavor intensity. ```swift // Top-selling donuts this month let popular = model.donuts(sortedBy: .popularity(.month)) // Alphabetical let alphabetical = model.donuts(sortedBy: .name) // Spiciest donuts first let spicy = model.donuts(sortedBy: .flavor(.spicy)) ``` -------------------------------- ### Linearly Interpolate Between Two Values Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Linearly interpolates between two values based on a percentage. The percent parameter blends from the starting value (0) to the destination value (1). Clamps the percent to 0-1 by default. ```swift let start = 0.0 let end = 100.0 let quarter = start.interpolate(to: end, percent: 0.25) // 25.0 let halfway = start.interpolate(to: end, percent: 0.5) // 50.0 let threequarter = start.interpolate(to: end, percent: 0.75) // 75.0 // Used in OrderGenerator for smoothing sales data let smoothedSales = previousSalesCount.interpolate( to: currentSalesCount, percent: 0.5 // 50% blend ) ``` -------------------------------- ### Request Live Activity for Order Preparation Source: https://github.com/apple/sample-food-truck/blob/main/README.md Initiates a Live Activity to display order preparation time. This code should be used when an order status changes to 'preparing'. Ensure the ActivityKit framework is imported. ```swift let timerSeconds = 60 let activityAttributes = TruckActivityAttributes( orderID: String(order.id.dropFirst(6)), order: order.donuts.map(\.id), sales: order.sales, activityName: "Order preparation activity." ) let future = Date(timeIntervalSinceNow: Double(timerSeconds)) let initialContentState = TruckActivityAttributes.ContentState(timerRange: Date.now...future) let activityContent = ActivityContent(state: initialContentState, staleDate: Calendar.current.date(byAdding: .minute, value: 2, to: Date())!) do { let myActivity = try Activity.request(attributes: activityAttributes, content: activityContent, pushType: nil) print(" Requested MyActivity live activity. ID: \(myActivity.id)") postNotification() } catch let error { print("Error requesting live activity: \(error.localizedDescription)") } ``` -------------------------------- ### Create a Bar Chart for Donut Sales Source: https://github.com/apple/sample-food-truck/blob/main/README.md This snippet demonstrates how to create a basic bar chart using `BarMark` to display donut sales data. It configures the chart's appearance, including corner radius, gradient fill, and adds annotations for sales figures. ```swift Chart { ForEach(sortedSales) { sale in BarMark( x: .value("Donut", sale.donut.name), y: .value("Sales", sale.sales) ) .cornerRadius(6, style: .continuous) .foregroundStyle(.linearGradient(colors: [Color("BarBottomColor"), .accentColor], startPoint: .bottom, endPoint: .top)) .annotation(position: .top, alignment: .top) { Text(sale.sales.formatted()) .padding(.vertical, 4) .padding(.horizontal, 8) .background(.quaternary.opacity(0.5), in: Capsule()) .background(in: Capsule()) .font(.caption) } } } ``` -------------------------------- ### Using BrandHeader Component Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/10-swiftui-components.md Demonstrates how to integrate the BrandHeader component into a SwiftUI view. Ensure FoodTruckKit is imported. ```swift import FoodTruckKit struct MyView: View { var body: some View { VStack { BrandHeader() // Rest of content } } } ``` -------------------------------- ### All Preset Toppings Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Access all predefined donut topping types. This static property provides an array of all available `Donut.Topping` instances. ```swift static let all: [Donut.Topping] // All 35 toppings ``` -------------------------------- ### Create Custom Donut View Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md Allows users to create a custom donut by selecting dough, glaze, and topping. Includes a live preview and flavor profile. Requires the FoodTruckModel environment object to add the donut to the catalog. ```swift struct DonutEditorView: View { @EnvironmentObject private var model: FoodTruckModel @State private var name = "My Creation" @State private var selectedDough: Donut.Dough = .plain @State private var selectedGlaze: Donut.Glaze? = .chocolate @State private var selectedTopping: Donut.Topping? = .sprinkles var previewDonut: Donut { Donut( id: -1, name: name, dough: selectedDough, glaze: selectedGlaze, topping: selectedTopping ) } var body: some View { Form { TextField("Donut Name", text: $name) Section("Dough") { Picker("Type", selection: $selectedDough) { ForEach(Donut.Dough.all, id: \.self) { Text(dough.name).tag(dough) } } } Section("Glaze") { Picker("Type", selection: $selectedGlaze) { Text("None").tag(Optional.none) ForEach(Donut.Glaze.all, id: \.self) { Text(glaze.name).tag(Optional(glaze)) } } } Section("Topping") { Picker("Type", selection: $selectedTopping) { Text("None").tag(Optional.none) ForEach(Donut.Topping.all, id: \.self) { Text(topping.name).tag(Optional(topping)) } } } Section("Preview") { HStack { Spacer() DonutView(donut: previewDonut) .frame(width: 80, height: 80) Spacer() } VStack(alignment: .leading, spacing: 8) { Text("Flavor Profile") .font(.headline) ForEach(Flavor.allCases, id: \.self) { HStack { Text(flavor.name) Spacer() Text("\(previewDonut.flavors[flavor])") .foregroundColor(.secondary) } } } } Button("Add to Catalog") { var newDonut = previewDonut newDonut.id = model.donuts.count model.updateDonut(id: newDonut.id, to: newDonut) } } .navigationTitle("Create Donut") } } ``` -------------------------------- ### Create Passkey Account Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Asynchronously registers a new passkey with a given username. Updates the currentUser property on success. Errors are logged but not thrown. ```swift await accountStore.createPasskeyAccount(authorizationController: controller, username: username, options: []) ``` -------------------------------- ### Sign into Passkey Account Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Asynchronously prompts the user for passkey or password sign-in. Updates the currentUser property on success. Errors are logged but not thrown. ```swift await accountStore.signIntoPasskeyAccount(authorizationController: controller, options: []) ``` -------------------------------- ### FoodTruckModel Initialization with OrderGenerator Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/04-order-generation.md Demonstrates how the FoodTruckModel initializer internally utilizes OrderGenerator to populate its order and sales summary properties. ```swift let model = FoodTruckModel() // Model has already generated: // - model.orders: Today's orders (with background generation of new orders) // - model.dailyOrderSummaries: Historical daily summaries per city // - model.monthlyOrderSummaries: Historical monthly summaries per city ``` -------------------------------- ### Build a Custom Donut Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Create a custom donut with specified dough, glaze, and topping. Access combined flavor profiles. ```swift let myDonut = Donut( id: 50, name: "Spicy Dream", dough: .lemonade, glaze: .spicy, topping: .spicySauceDrizzle ) // Combine flavors let profile = myDonut.flavors print("Spiciness: \(profile.spicy)") // Sum of all three components ``` -------------------------------- ### Initialize FoodTruckApp Model Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md Initializes the FoodTruckApp with the FoodTruckModel. The model automatically loads preset donuts, generates sample orders, and creates historical summaries. ```swift import FoodTruckKit import SwiftUI @main struct FoodTruckApp: App { @StateObject private var model = FoodTruckModel() var body: some Scene { WindowGroup { ContentView() .environmentObject(model) } } } ``` -------------------------------- ### All Preset Donuts Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Provides an array containing all 17 predefined donut instances. ```swift static let all: [Donut] = [ classic, blueberryFrosted, strawberryDrizzle, cosmos, strawberrySprinkles, lemonChocolate, rainbow, picnicBasket, figureSkater, powderedChocolate, powderedStrawberry, custard, superLemon, fireZest, blackRaspberry, daytime, nighttime ] ``` -------------------------------- ### Ingredient.image Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Loads a SwiftUI Image for an ingredient, with an option to load either a thumbnail or the full-size version. ```APIDOC ## Ingredient.image ### Description Load a SwiftUI Image for the ingredient. ### Signature ```swift func image(thumbnail: Bool) -> Image ``` ### Parameters #### Path Parameters - **thumbnail** (Bool) - Required - If true, loads the thumbnail version; if false, loads full-size ### Returns - **Image** - SwiftUI Image asset ### Asset Naming `"{imageAssetPrefix}/{imageAssetName}-{full|thumb}"` ### Example ```swift let dough: Donut.Dough = .chocolate let thumbImage = dough.image(thumbnail: true) // "dough/brown-thumb" let fullImage = dough.image(thumbnail: false) // "dough/brown-full" ``` ``` -------------------------------- ### Load Ingredient Image (SwiftUI) Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Loads a SwiftUI Image for an ingredient, with options for thumbnail or full-size versions. Asset naming follows a specific pattern. ```swift func image(thumbnail: Bool) -> Image let dough: Donut.Dough = .chocolate let thumbImage = dough.image(thumbnail: true) // "dough/brown-thumb" let fullImage = dough.image(thumbnail: false) // "dough/brown-full" ``` -------------------------------- ### Update Relying Party ID Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Placeholder comment for updating the relying party ID. Replace 'example.com' with your actual domain. ```swift // Replace "example.com" with your actual domain ``` -------------------------------- ### Order Model Documentation Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md This section details the structure and functionality of the Order model, including its properties, computed properties, and public methods available for direct use. ```APIDOC ## Order Model **Location**: `FoodTruckKit/Sources/Order/Order.swift` **Type**: Public struct, conforms to `Identifiable`, `Equatable` Represents a single customer order with status, items, and metadata. ### Properties | Property | Type | Description | |----------|------|-------------| | `id` | `String` | Unique identifier (format: `"Order#NNNNN"`) | | `status` | `OrderStatus` | Current stage: placed, preparing, ready, completed | | `donuts` | `[Donut]` | List of donut objects in this order | | `sales` | `[Donut.ID: Int]` | Count of each donut ID sold in this order | | `grandTotal` | `Decimal` | Total price | | `city` | `City.ID` | Destination city | | `parkingSpot` | `ParkingSpot.ID` | Parking spot ID at destination | | `creationDate` | `Date` | When order was placed | | `completionDate` | `Date?` | When order was completed (nil if incomplete) | | `temperature` | `Measurement` | Ambient temperature at creation | | `wasRaining` | `Bool` | Weather condition at creation | ### Computed Properties | Property | Type | Description | |----------|------|-------------| | `duration` | `TimeInterval?` | Elapsed time from creation to completion (nil if incomplete) | | `totalSales` | `Int` | Sum of all donut quantities in `sales` | | `isPreparing` | `Bool` | True if status == .preparing | | `isComplete` | `Bool` | True if status == .completed | | `formattedDate` | `String` | Localized string: "Today, 2:30 PM" or "Yesterday" or "6/22/2026, 2:30 PM" | ### Public Methods | Method | Signature | Returns | Description | |--------|-----------|---------|-------------| | `init(id:status:donuts:sales:grandTotal:city:parkingSpot:creationDate:completionDate:temperature:wasRaining:)` | — | — | Full initializer with all fields | | `markAsComplete()` | — | — | Set status to .completed and completionDate to now (idempotent) | | `markAsNextStep(completion:)` | `(OrderStatus) -> Void` | — | Transition status: placed → preparing → completed. Calls completion block with new status | | `markAsPreparing()` | — | — | Set status to .preparing (idempotent) | | `matches(searchText:)` | `String` | `Bool` | Case-insensitive search matching order ID | ### Usage Example ```swift var order = Order( id: "Order#001234", status: .placed, donuts: [donut1, donut2], sales: [1: 2, 3: 1], grandTotal: 15.89, city: City.cupertino.id, parkingSpot: City.cupertino.parkingSpots[0].id, creationDate: .now, completionDate: nil, temperature: .init(value: 72, unit: .fahrenheit), wasRaining: false ) // Transition order status order.markAsNextStep { newStatus in print("Order is now: \(newStatus.title)") } // Check readiness if order.isPreparing { startCountdown() } ``` ``` -------------------------------- ### Initialize OrderGenerator and Generate Today's Orders Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/04-order-generation.md Instantiate OrderGenerator with a donut catalog and generate a list of orders for the current day. These orders can then be accessed and displayed. ```swift let generator = OrderGenerator(knownDonuts: Donut.all) let todayOrders = generator.todaysOrders() // Access generated orders ForEach(todayOrders) { order in Text("\(order.id): \(order.totalSales) items") } ``` -------------------------------- ### BinaryFloatingPoint Extensions Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/06-layouts-utilities.md Extensions on `BinaryFloatingPoint` for various easing functions, percentage calculations, and value mapping. ```APIDOC ## `easeInOut(clamped:) -> Self` ### Description Smooth easing function: 0 → 1 with ease-in/ease-out curve. Formula: `t² × (3 - 2t)` where t is clamped input. ### Parameters #### Path Parameters - **clamped** (Bool) - Optional - Default: `true` - Clamp input to 0–1 ### Returns Eased value (0 to 1) ### Example ```swift let progress = 0.5 let eased = progress.easeInOut() // ~0.5 (symmetric point) // Typical animation curve // 0.0 → 0.0 (instant start) // 0.25 → 0.11 (accelerating) // 0.5 → 0.5 (midpoint) // 0.75 → 0.89 (decelerating) // 1.0 → 1.0 (instant end) ``` ## `symmetricEaseInOut(clamped:) -> Self` ### Description Easing that accelerates to 1 then decelerates back to 0. Useful for pulse animations. ### Parameters #### Path Parameters - **clamped** (Bool) - Optional - Default: `true` - Clamp input to 0–1 ### Returns Value that peaks at 0.5, zero at 0 and 1 ### Example ```swift let progress = 0.5 let pulse = progress.symmetricEaseInOut() // 1.0 (peak) // Profile // 0.0 → 0.0 (start) // 0.25 → 0.5 (halfway to peak) // 0.5 → 1.0 (peak) // 0.75 → 0.5 (halfway back) // 1.0 → 0.0 (end) ``` ## `percent(truncation:) -> Self` ### Description Calculate the percentage of a value within a truncation cycle. ### Parameters #### Path Parameters - **truncation** (Self) - Required - The cycle period ### Returns Fractional part as percentage (0–1) ### Example ```swift let progress = 175.0 let pct = progress.percent(truncation: 50) // 0.5 (175 % 50 = 25; 25/50 = 0.5) ``` ## `map(to:clamped:) -> Self` ### Description Map a percentage to a range. Inverse of `range.percent(for:)`. ### Parameters #### Path Parameters - **range** (ClosedRange) - Required - Target range - **clamped** (Bool) - Optional - Default: `true` - Clamp result ### Returns Value within range ### Example ```swift let progress = 0.75 // 75% let value = progress.map(to: 0.0...100.0) // 75.0 ``` ## `remap(from:to:clamped:) -> Self` ### Description Map a value from one range to another, preserving its relative position. ### Parameters #### Path Parameters - **originalRange** (ClosedRange) - Required - Source range - **newRange** (ClosedRange) - Required - Target range - **clamped** (Bool) - Optional - Default: `true` - Clamp result ### Returns Mapped value in newRange ### Example ```swift let value = 500.0 // In range 0–1000 let remapped = value.remap(from: 0...1000, to: 0...100) // 50.0 ``` ## `interpolate(to:percent:clamped:) -> Self` ### Description Linear interpolation between two values. ### Parameters #### Path Parameters - **destination** (Self) - Required - Target value - **percent** (Self) - Required - Blend percentage (0 = self, 1 = destination) - **clamped** (Bool) - Optional - Default: `true` - Clamp percent to 0–1 ### Returns Interpolated value ### Example ```swift let start = 0.0 let end = 100.0 let mid = start.interpolate(to: end, percent: 0.5) // 50.0 ``` ``` -------------------------------- ### Create Password Account Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Asynchronously creates a password-based account. Immediately sets the currentUser to .authenticated(username:). ```swift await accountStore.createPasswordAccount(username: username, password: password) ``` -------------------------------- ### Define Navigation Structure with NavigationSplitView Source: https://github.com/apple/sample-food-truck/blob/main/README.md Sets up a split view navigation interface with a sidebar and a navigation stack for the detail view. Use this to create master-detail interfaces in SwiftUI. ```swift NavigationSplitView { Sidebar(selection: $selection) } detail: { NavigationStack(path: $path) { DetailColumn(selection: $selection, model: model) } } ``` -------------------------------- ### OrderSummary Methods Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/INDEX.md Methods for creating and combining order summaries, including initializing with sales data and merging with other summaries or orders. ```APIDOC ## OrderSummary Methods ### Description Methods for creating and combining order summaries. ### Methods - `init(sales:)` - `union(_: OrderSummary) -> OrderSummary` - `formUnion(_: OrderSummary) -> void` - `union(_: Order) -> OrderSummary` - `formUnion(_: Order) -> void` ### Static Constants - `empty: OrderSummary` ``` -------------------------------- ### User Authentication View with Passkey Option Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md This SwiftUI view handles user authentication, allowing users to sign in or create an account. It supports signing in with a Passkey and presents a sign-up sheet when requested. ```swift struct AccountViewWithAuth: View { @StateObject private var accountStore = AccountStore() @State private var showingSignUp = false var body: some View { if accountStore.isSignedIn { if case .authenticated(let username) = accountStore.currentUser { VStack { Text("Welcome, \(username)") .font(.title) Button("Sign Out") { accountStore.signOut() } .buttonStyle(.destructive) } } } else { VStack(spacing: 20) { Text("Sign In to Save Your Progress") .font(.title2) Button("Sign In with Passkey") { signInWithPasskey() } Button("Create Account") { showingSignUp = true } } .sheet(isPresented: $showingSignUp) { SignUpView(accountStore: accountStore) } } } private func signInWithPasskey() { Task { let controller = ASAuthorizationController( authorizationRequests: [ // Create passkey requests ] ) controller.presentationContextProvider = /* view controller */ await accountStore.signIntoPasskeyAccount(authorizationController: controller) } } } ``` -------------------------------- ### Iterate Over Donut Ingredients Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Loop through all ingredients of a donut to access their names, flavor profiles, and generate thumbnails. ```swift for ingredient in donut.ingredients { print("\(ingredient.name): \(ingredient.flavors)") let image = ingredient.image(thumbnail: true) } ``` -------------------------------- ### Animate Progress View with Interpolation Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md Demonstrates animating a ProgressView using the easeInOut interpolation. A button triggers the animation to progress from 0.0 to 1.0 over 3 seconds. ```swift struct InterpolatedProgressView: View { @State private var progress = 0.0 var body: some View { VStack { ProgressView(value: progress.easeInOut()) Button("Animate") { withAnimation(.easeInOut(duration: 3)) { progress = 1.0 } } } } } ``` -------------------------------- ### All Preset Glazes Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Access all predefined donut glaze types. This static property provides an array of all available `Donut.Glaze` instances. ```swift static let all: [Donut.Glaze] = [ blueberry, chocolate, sourCandy, spicy, strawberry, lemon, rainbow ] ``` -------------------------------- ### FlavorProfile Methods and Subscript Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/INDEX.md Methods and subscript for accessing and manipulating flavor profiles, including combining profiles and getting/setting specific flavor values. ```APIDOC ## FlavorProfile Methods and Subscript ### Description Methods and subscript for accessing and manipulating flavor profiles. ### Methods - `union(with:) -> FlavorProfile` - `formUnion(with:) -> void` ### Subscript - `[flavor: Flavor] -> Int` (get/set) ``` -------------------------------- ### Create Passkey Account Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Creates a new passkey account for a user. This function requires an authorization controller and the desired username. After creation, the user is considered authenticated. ```swift let controller = ASAuthorizationController(authorizationRequests: [...]) await accountStore.createPasskeyAccount( authorizationController: controller, username: "alice@example.com" ) // User is now authenticated switch accountStore.currentUser { case .authenticated(let username): print("Account created: \(username)") default: break } ``` -------------------------------- ### Fetch Weather Data for Parking Spots Source: https://github.com/apple/sample-food-truck/blob/main/README.md This Swift code snippet fetches current weather conditions, rain forecast, cloud cover, temperature, and symbol name for a given location. It also retrieves attribution information for WeatherKit. Use this to display real-time weather relevant to parking spots. ```swift .task(id: city.id) { for parkingSpot in city.parkingSpots { do { let weather = try await WeatherService.shared.weather(for: parkingSpot.location) condition = weather.currentWeather.condition willRainSoon = weather.minuteForecast?.contains(where: { $0.precipitationChance >= 0.3 }) cloudCover = weather.currentWeather.cloudCover temperature = weather.currentWeather.temperature symbolName = weather.currentWeather.symbolName let attribution = try await WeatherService.shared.attribution attributionLink = attribution.legalPageURL attributionLogo = colorScheme == .light ? attribution.combinedMarkLightURL : attribution.combinedMarkDarkURL if willRainSoon == false { spot = parkingSpot break } } catch { print("Could not gather weather information...", error.localizedDescription) condition = .clear willRainSoon = false cloudCover = 0.15 } } } ``` -------------------------------- ### Format Order Creation Date Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Provides a localized string representation of the order's creation date. Formats the date based on whether it was created today, yesterday, or on a different date. ```swift // Example usage is not provided in the source, but the property returns a formatted string like: // "Today, 2:30 PM" // "Yesterday, 9:15 AM" // "6/22/2026, 4:45 PM" ``` -------------------------------- ### Order Methods Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/INDEX.md Methods for manipulating and querying individual order objects, including marking orders as complete or in progress, and checking their status. ```APIDOC ## Order Methods ### Description Methods for manipulating and querying individual order objects, including status updates and matching search criteria. ### Methods - `init(id:status:donuts:sales:grandTotal:city:parkingSpot:creationDate:completionDate:temperature:wasRaining:)` - `markAsComplete() -> void` - `markAsNextStep(completion:) -> void` - `markAsPreparing() -> void` - `matches(searchText:) -> Bool` ``` -------------------------------- ### Access FlavorProfile Properties Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Demonstrates how to access and modify flavor intensities using subscript notation on a FlavorProfile instance. Requires an initialized FlavorProfile object. ```swift let profile = FlavorProfile(sweet: 3, spicy: 1) let sweetness = profile[.sweet] // 3 profile[.spicy] = 2 ``` -------------------------------- ### AccountStore.signIntoPasskeyAccount Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Prompts the user for passkey or password sign-in using the provided AuthorizationController. It updates the currentUser property upon successful authentication and logs any errors encountered without throwing exceptions. ```APIDOC ## signIntoPasskeyAccount ### Description Asynchronously prompts the user for passkey or password sign-in. Updates `currentUser` on success. Logs errors (no exception thrown). ### Signature signIntoPasskeyAccount(authorizationController: ASAuthorizationController, options: ASAuthorizationController.RequestOptions = []) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Updates `currentUser` property. #### Response Example None ### Throws None (errors are logged) ``` -------------------------------- ### AccountStore.createPasswordAccount Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Creates a new account using a username and password. It immediately sets the currentUser property to the authenticated user upon successful creation. ```APIDOC ## createPasswordAccount ### Description Asynchronously creates a password-based account. Sets `currentUser = .authenticated(username:)` immediately. ### Signature createPasswordAccount(username: String, password: String) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Sets `currentUser = .authenticated(username:)`. #### Response Example None ### Throws None (errors are logged) ``` -------------------------------- ### Preset Doughs Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Defines all available preset donut dough types. This static property provides an array of `Donut.Dough` instances, each with its specific name, asset, flavors, and background color. ```swift static let all: [Donut.Dough] = [ blueberry, chocolate, sourCandy, strawberry, plain, powdered, lemonade ] ``` -------------------------------- ### Reference Image Assets in Swift Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/08-package-manifest.md Reference image assets using bundle-relative paths. The `bundle: .module` ensures images are loaded from the FoodTruckKit package bundle, and assets are organized by type. ```swift Image("\(imageAssetPrefix)/\(assetName)-full", bundle: .module) ``` -------------------------------- ### Predefined Cities in Swift Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/02-models.md Provides static properties for all predefined cities and a method to identify a city by its ID. Use this to access the list of all cities or to retrieve a specific city. ```swift static let all: [City] = [ cupertino, sanFrancisco, london ] static func identified(by id: City.ID) -> City ``` -------------------------------- ### ClosedRange Extensions Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/06-layouts-utilities.md Extensions on `ClosedRange` for mapping percentages to values and vice-versa. ```APIDOC ## `value(percent:clamped:) -> Bound` ### Description Map a percentage (0–1) to a value within the range. ### Parameters #### Path Parameters - **percent** (Bound) - Required - Value from 0 to 1 - **clamped** (Bool) - Optional - Default: `true` - Clamp percent to 0–1 ### Returns A value between `lowerBound` and `upperBound` ### Example ```swift let range = 0.0...100.0 let value = range.value(percent: 0.5) // 50.0 ``` ## `percent(for:clamped:) -> Bound` ### Description Calculate what percentage a value represents within the range. ### Parameters #### Path Parameters - **value** (Bound) - Required - A value within the range - **clamped** (Bool) - Optional - Default: `true` - Clamp result to 0–1 ### Returns A percentage from 0 to 1 ### Example ```swift let range = 0.0...100.0 let pct = range.percent(for: 25.0) // 0.25 ``` ``` -------------------------------- ### Monitor Sign-In State in SwiftUI Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Observes the authentication state of the user and displays either the main view for authenticated users or the sign-in view for unauthenticated users. ```swift struct ContentView: View { @ObservedObject var accountStore: AccountStore var body: some View { if accountStore.isSignedIn { MainView(user: accountStore.currentUser) } else { SignInView(accountStore: accountStore) } } } ``` -------------------------------- ### OrderStatus Comparable Conformance Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Demonstrates the comparison operators for OrderStatus, which conforms to Comparable based on its raw value. Used for sorting orders by progress. ```swift OrderStatus.placed < OrderStatus.preparing // true OrderStatus.ready < OrderStatus.completed // true OrderStatus.placed < OrderStatus.completed // true ``` -------------------------------- ### Apply Symmetric Ease-In/Ease-Out Timing Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/12-extension-methods.md Applies easing that accelerates to 1 at 0.5, then decelerates back to 0, producing a pulse or bounce effect. Ideal for pulsing animations. Clamps input to 0-1 by default. ```swift for step in stride(from: 0.0, through: 1.0, by: 0.1) { let pulse = step.symmetricEaseInOut() print("Input: \(step), Pulse: \(pulse)") // 0.0 → 0.0 (start) // 0.25 → 0.5 (rising) // 0.5 → 1.0 (peak) // 0.75 → 0.5 (falling) // 1.0 → 0.0 (end) } // Perfect for pulsing animations: Circle() .scaleEffect(1.0 + progress.symmetricEaseInOut() * 0.2) ``` -------------------------------- ### Ingredient Protocol Extension Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/03-ingredients.md Provides default implementations for the `id` property and an `image` method for the Ingredient protocol. The `id` is derived from the asset prefix and name, while the `image` method constructs image names based on thumbnail status. ```swift extension Ingredient { var id: String { "\(Self.imageAssetPrefix)/\(name)" } func image(thumbnail: Bool) -> Image // Returns Image("\(prefix)/\(assetName)-{full|thumb}") } ``` -------------------------------- ### Animate Donut View with Pulsing Effect Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/11-sample-code.md Shows how to create a pulsing animation for a DonutView using scale effects and SwiftUI's animation modifiers. The animation repeats indefinitely. ```swift struct PulsingDonutView: View { @State private var pulse = 0.0 var body: some View { DonutView(donut: .classic) .scaleEffect(1.0 + pulse.symmetricEaseInOut() * 0.3) .onAppear { withAnimation(.linear(duration: 2).repeatForever(autoreverses: false)) { pulse = 1.0 } } } } ``` -------------------------------- ### State Management with @StateObject Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/10-swiftui-components.md Demonstrates using @StateObject to manage the FoodTruckModel, which holds order data. Use this pattern to initialize and observe observable objects within a view's lifecycle. ```swift @StateObject private var model = FoodTruckModel() // Use model properties in views ForEach(model.orders) { order in OrderRow(order: order) } ``` -------------------------------- ### AccountStore.createPasskeyAccount Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/05-authentication.md Registers a new passkey for the user with the specified username. It updates the currentUser property upon successful registration and logs any errors encountered. ```APIDOC ## createPasskeyAccount ### Description Asynchronously registers a new passkey with the given username. Updates `currentUser` on success. Logs errors. ### Signature createPasskeyAccount(authorizationController: ASAuthorizationController, username: String, options: ASAuthorizationController.RequestOptions = []) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Updates `currentUser` property. #### Response Example None ### Throws None (errors are logged) ``` -------------------------------- ### Platform-Specific Code Compilation Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/08-package-manifest.md Guard platform-specific code using preprocessor directives. This allows the package to build on all platforms while restricting certain APIs (like AccountStore and user-facing auth UI) to specific operating systems. ```swift #if os(iOS) || os(macOS) // AccountStore and user-facing auth UI #endif ``` -------------------------------- ### OrderGenerator Methods Source: https://github.com/apple/sample-food-truck/blob/main/_autodocs/INDEX.md Methods for generating orders, including generating today's orders, specific orders with custom parameters, and historical order summaries. ```APIDOC ## OrderGenerator Methods ### Description Methods for generating orders, including today's orders, specific orders, and historical order summaries. ### Methods - `init(knownDonuts:)` - `todaysOrders() -> [Order]` - `generateOrder(number:date:) -> Order` - `generateOrder(number:date:generator:) -> Order` - `historicalDailyOrders(since:cityID:) -> [OrderSummary]` - `historicalMonthlyOrders(since:cityID:) -> [OrderSummary]` ```