Reading and Troubleshooting AI-Generated Swift Code
This guide is a companion to the Dice Foundry course. It teaches you to read Swift code that an AI assistant wrote for you, decide whether you can trust it, and find out why it fails when it does not work. You already know how to review a change someone else made to a production system: you ask what changed, what it depends on, and what evidence says it works. The same habits apply here. This guide supplies the Swift-specific parts.
How to use this guide
- Read Parts 1 through 4 once, before you next ask an assistant for code.
- Keep Part 5 (the review checklist) beside Xcode when you paste generated code into a project.
- Use Part 6 when the build fails or the app misbehaves.
- All Swift snippets here are illustrative (
swift-example). They are not part of the Dice Foundry project, and nothing in this guide was compiled or run to produce it. The examples show shapes of code to recognize, not code to paste. - The toolchain the course documents is Xcode 27.2, the Swift 6.4 compiler in Swift 5 language mode, and an iOS 17.0 minimum deployment target. (Those toolchain versions are the course's own statement and were not checked against Apple's documentation for this guide; not verified; check Apple's documentation.) If your setup differs, the checks below still apply; only the specifics change.
The course's reference checkpoints were compiled and tested before publication. The results are summarized in the course README. This guide does not repeat them, and it makes no claim that any generated code you receive has been built or tested. Treat that as something you establish yourself, using Part 4.
Part 1 — Start from a known checkpoint
Why a checkpoint matters
A language model writes code that looks right. It does not run Xcode. When it says "this compiles", it is describing what it expects, not reporting something it observed, unless it shows you real tool output (see Part 4). The most reliable way to judge its code is to compare it with a version you already understand and have already run.
Dice Foundry gives you thirteen of those. Each chapter ends with a checkpoint: a complete, working project folder in Reference-Checkpoints/. Chapter 14's final project has a solution in the answer key. Use them as a ruler.
Match the code to a checkpoint
Before you read any generated code line by line, answer one question: which stage of the project is this code written for? Look for these markers.
| What you see in the generated code | Stage it belongs to |
|---|---|
One ContentView that holds @State for the result, the die, the quantity, and the modifier, and calls its own rollDie function |
Checkpoints 4 to 8 |
A RollResult struct with Identifiable, and a history array in ContentView |
Checkpoint 8 |
Codable on DieType and RollResult, plus a HistoryStore that reads and writes a JSON file |
Checkpoint 9 |
Separate files for DieButton, DiePicker, RollOptionsView, ResultView, HistoryRow, and @Binding parameters |
Checkpoint 10 |
A Theme type, asset-catalog colors, @ScaledMetric, accessibility labels, @AppStorage |
Checkpoint 11 |
A DiceRoller that takes its random source as a parameter, and a test target |
Checkpoint 12 |
A RollViewModel marked @Observable that ContentView creates with @State |
Checkpoint 13 |
Then compare in three ways.
- Same file layout? If the assistant created a
Servicesfolder, aRepositoryprotocol, and aCoordinatorfor a project that has the Checkpoint 8 layout, it is solving a problem you do not have. Chapter 13 explains why you add structure only when the code has outgrown the simpler form. - Same names? Dice Foundry uses
DieType,RollResult,HistoryStore,DiceRoller, andRollViewModel. Generated code that renames them, or inventsDiceManagerandRollEngine, is not extending your project. It is replacing it. - Same data flow? Use the roll-flow diagram in the Student Workbook, which shows the same steps. A button press calls a function, the function produces a
RollResult, the result goes into history, history is saved, and the state change makes SwiftUI redraw. Find each of those steps in the generated code. A step that is missing is a bug. A step that appears twice is a likely bug.
Use a diff, not a feeling
Put the generated version beside your last working version and look at only what changed. In Xcode you can use the Source Control navigator, or in Terminal:
git diff
Run this after you paste. A one-line request that produces a diff touching nine files is a signal to stop and ask why. The course follows the same rule from the other side: every hunk in a chapter's diff must correspond to a numbered step you can read and explain.
Make a Git commit of your working project before you paste generated code. If the result is worse, you can discard it with one command and you lose nothing. The Development Checkpoint at the end of each chapter shows how.
Part 2 — Reading generated Swift
Read it the way the course reads code
Every chapter contains a section called "Reading This Like a Developer". Use that same method on generated code. Ask these questions in this order.
- Where does execution begin? In a SwiftUI app, find the type marked
@main, then itsWindowGroup, then the first view. - What does the button call? Find the closure or function a
Buttonruns. - Which values are state? Find
@State,@Binding,@AppStorage,@Observable, and@Environment. These are the values whose changes redraw the screen. - Where does each value start, and where does it change? A value that is only ever set in one place is easy to reason about. A value changed in five places is where bugs live.
- Where is data saved, and what happens if saving fails?
- Which code is rules (business logic) and which is presentation? Dice totals are rules. A color is presentation. Generated code often mixes them in one
body.
Write the answers down in a few lines. If you cannot answer a question, that is the part to ask the assistant about, or to rewrite yourself.
Patterns that often appear in generated code
These are common, valid Swift. Recognize them so they do not stop you.
guard for early exit. The course mentions it in Chapter 9 but does not use it.
func load() {
guard let data = try? Data(contentsOf: fileURL) else { return }
// data is available for the rest of the function
}
Read it as "if this fails, leave now." Be aware that try? turns an error into nil and discards the reason. Dice Foundry uses do and catch so that the error is visible. A generated try? is not wrong, but it means failures disappear silently.
Force unwraps and implicit trust. A ! after a value, such as value!, crashes the app if the value is empty. A try! crashes if the call throws. A force cast as! crashes if the type is wrong. These are acceptable in a throwaway playground and are warning signs in an app.
async and await. You will see these in network or file code. The course does not need them. If a generated change introduces async, Task, or actor into a project that had none, ask why. Often it is unnecessary.
Closures with $0. history.filter { $0.die == .d20 } is short for a closure that receives each element. Chapter 14 explains the filter form.
Generic and protocol-heavy code. Phrases like some View, any Storage, associatedtype, and where Element: Identifiable are legitimate. They are also the usual sign of the over-engineering described next.
Spotting over-built code
The course's goal includes spotting overcomplicated code. These are the usual signs.
- A protocol with one implementation. A
HistoryStoringprotocol is useful if you have a real and a fake store, as Chapter 12 does for testing the random source. Without a second implementation or a test that needs it, it adds a file and removes nothing. - Two copies of the same data. Chapter 14 warns about a
filteredRollsarray stored besidehistory. Copies drift apart. A computed property avoids the copy. - A view model for a screen that has no logic. Chapter 13 introduces
RollViewModelonly afterContentViewhas grown too large. - New dependencies. The course uses no third-party packages. A suggestion to add a package for something the standard library does in four lines needs a strong reason.
- Wrapper types around single values. A
DiceCountstruct that holds oneIntand does nothing else. - Comments that restate the code.
// increment countabovecount += 1tells you the author was filling space.
When generated code feels like too much, say so in the request: "Do this inside the existing ContentView with no new files and no new types." Then compare the result with the checkpoint for your stage. Directing the assistant to the smallest change that works is usually faster than reading and removing the extra layers afterward.
Spotting code for the wrong version
Models are trained on years of Swift. They mix eras. Generated code often uses patterns that Apple has since replaced, and sometimes patterns too new for your target. The next two parts cover the checks.
Part 3 — What to check: compile, target, APIs, language mode
Check 1 — Does it compile?
The compiler is the first and cheapest reviewer. Press ⌘B in Xcode to build. Do not rely on the live preview alone. The preview can show an older rendering after the code has changed, and it does not build the test target.
Read the first error, not the last. One missing brace or one wrong name can produce many follow-on messages. Fix the first, build again, and repeat. Chapter 12 shows seven broken examples, with their messages, so you can practice. Exact wording varies between Xcode versions, so treat the messages in the course as "similar to" what you will see.
Also read the warnings. Generated code that builds with new warnings is telling you something: an unused variable, a deprecated API, or a conversion the compiler is unsure of.
A clean build means the code is valid Swift for your settings. It does not mean the app does what you asked. A build that succeeds is only the first gate.
Check 2 — Does it respect the deployment target?
The deployment target is the oldest iOS version your app promises to run on. The course sets it to iOS 17.0 because @Observable, .sensoryFeedback, and the two-parameter form of onChange need it. An API added later than iOS 17.0 either fails to build or needs a guard.
Find the setting in Xcode: select the project, select the app target, and open the General tab, where it appears under Minimum Deployments. The build setting is IPHONEOS_DEPLOYMENT_TARGET. Confirm it says 17.0 before you start judging APIs.
When you use an API that is newer than your target, Xcode reports an error similar to "is only available in iOS 18.0 or newer". Do not respond by raising the deployment target to silence it. That decision changes who can run your app, and it is yours to make, not the assistant's. Either choose a different approach or wrap the new call, as the next section shows.
if #available(iOS 18.0, *) {
// call the newer API here
} else {
// fall back to something that works on iOS 17
}
This form is real Swift. Use it deliberately and keep the fallback honest, because the fallback is the code that older devices will actually run, and you cannot test it without an older simulator.
Check 3 — APIs newer than iOS 17.0
You cannot memorize availability for every API. Use a short procedure for each unfamiliar API in generated code.
- Option-click the name in Xcode to see its summary. The quick help panel often lists the platforms and versions.
- Search Apple's developer documentation for the type or modifier. Each page lists availability near the top.
- Build against your deployment target. The compiler is the final authority for the SDK you have installed.
The list below gives names that commonly appear in generated code and are newer than iOS 17.0. Each availability value was read from the symbol's page on developer.apple.com (its availability metadata) when this guide was checked. Availability can change between SDK releases, so confirm in Apple's documentation for your SDK.
| API or feature | Apple's listed iOS availability | Note |
|---|---|---|
Tab (the structure used inside TabView) |
iOS 18.0 and later | The page lists iOS 18.0, macOS 15.0, visionOS 2.0. Older code uses .tabItem. |
MeshGradient |
iOS 18.0 and later | Not available on 17. |
.presentationSizing(_:) |
iOS 18.0 and later | Not on 17. |
.glassEffect(_:in:) (Liquid Glass) |
iOS 26.0 and later | Not available before 26. |
Observations (an AsyncSequence that tracks changes of @Observable types) |
iOS 26.0 and later | Distinct from the @Observable macro, which Apple lists at iOS 17.0. |
@Previewable does not belong in that list. Apple's page for the macro lists it at iOS 17.0 and later, so it is not newer than your deployment target. The page does not say which Xcode version introduced it; not verified; check Apple's documentation.
APIs that Apple lists at iOS 17.0 and that are part of the course include @Observable (the Observable() macro), .sensoryFeedback(_:trigger:), and onChange(of:initial:_:), which is the form with a zero-parameter or two-parameter closure. SwiftData's framework page also lists iOS 17.0, which is why Chapter 9 describes it as an alternative to the JSON file without building on it.
Now the other direction: older patterns the assistant may use that still compile but that the course does not teach.
ObservableObject,@Published,@StateObject, and@ObservedObjectare an older way to share observed state. Dice Foundry uses@Observableinstead. Mixing the two in one project is a common source of confusion. (Whether Apple has deprecated these types was not verified; check Apple's documentation.)NavigationViewis the older navigation container. Current code usesNavigationStack. Apple'sNavigationViewpage lists availability from iOS 13.0 to 27.3.0, which marks it as no longer current; check Apple's documentation for its status in your SDK..foregroundColor(...)appears on Apple's "Deprecated modifiers" page for SwiftUI, and.foregroundStyle(...)(iOS 15.0 and later) is the form to use. Apple's page for.foregroundColor(_:)lists iOS 13.0 to 27.3.0, so it still builds for your target.- The one-parameter
onChange(of:perform:) { newValue in ... }is deprecated in favor of the forms that take either zero or two parameters. Apple lists it as iOS 14.0 to 17.0 (deprecated at iOS 17.0), and it also appears on the "Deprecated modifiers" page. The replacementonChange(of:initial:_:)is listed at iOS 17.0 and later.
None of these breaks the build on its own. The cost is that your project ends up written in two styles, and you will not know which one a future change should follow. Choose the style your checkpoint already uses.
Check 4 — Swift 5 versus Swift 6 language mode
Swift has a language mode that is separate from the compiler version. The compiler can build a project in Swift 5 mode or Swift 6 mode. The setting is SWIFT_VERSION in the project's build settings, under Swift Language Version, which Apple's build settings reference describes as "the language version used to compile the target's Swift code." (That the Swift 6.4 compiler offers both modes was not verified; not verified; check Apple's documentation.)
Dice Foundry uses Swift 5 mode. Whether the Xcode template sets that by default was not verified; check Apple's documentation. The course also mentions that the app target uses a default actor isolation of MainActor and that the test target does not (Chapter 13 explains this). Apple's build settings reference lists SWIFT_DEFAULT_ACTOR_ISOLATION (Default Actor Isolation) and says that when it is set to MainActor, @MainActor isolation is inferred by default for unannotated code. The Swift migration guide describes Swift 6 checking as something you can enable incrementally while remaining in Swift 5 mode. Generated code written for one mode can fail or warn in the other.
Signs that generated code was written for Swift 6 mode:
@MainActoron types or functions,Sendableconformances,nonisolated,actor, or@preconcurrency.- Global
vardeclarations written asnonisolated(unsafe).
The claims that these compile in Swift 5 mode, and that global mutable vars, shared mutable singletons, and callbacks that cross threads without Sendable produce errors or warnings in Swift 6 mode, were not verified; check Apple's and swift.org's documentation. Treat the lists above as signs to ask about, not as proof of which mode the code targets.
The practical rules:
- Check which language mode your project uses before you judge any concurrency error.
- Do not change the language mode to make an error disappear. Moving to Swift 6 mode is a project decision with a long tail of changes.
- If the assistant adds
@MainActoreverywhere, or@unchecked Sendable, ask what problem it is solving. In Swift 5 mode with the course's default isolation, the answer is often "none." @unchecked Sendableandnonisolated(unsafe)tell the compiler to stop checking. They are an assertion that you know better. Treat them as a red flag in code you do not understand.
To see what Swift 6 mode reports for a project, open the project in Xcode, select the app target, open Build Settings, search for Swift Language Version, set it to Swift 6, and press ⌘B. Expect new errors, read them as a list of things to decide, and set the setting back to Swift 5 if you are not ready to change the project. This guide does not report the result for the course code.
Check 5 — Are there tests, and do they test anything?
From Chapter 12 on, the project has a test target using Swift Testing: import Testing, @Test, and #expect. When an assistant provides tests, apply three questions.
- Do they run? Press ⌘U. Tests that are not in a test target, or that use the older XCTest style in a project set up for Swift Testing, may not run at all. A test that never ran proves nothing.
- Could each one fail? Chapter 12's AI callout describes the typical empty test: it calls a function, stores the result, and asserts that the result equals itself. Ask what change to the code would make the test red. If nothing would, the test is decoration.
- Does it check a rule from your requirements? "3D6 + 2 with dice 4, 2, and 6 totals 14" is a rule. "The function returns something" is not.
Mutation is the best practical probe. Break the code on purpose, for example change + modifier to - modifier in the total. Run the tests. If they still pass, they were not checking the total.
Tests also have limits. Chapter 12 explains that a forgotten saveHistory() in clearHistory() cannot be caught by a test of DiceRoller. For behavior that lives in the view, you still need a manual script: run, roll, relaunch, and check.
Part 4 — A claim of testing versus real test output
The phrases to distrust
An assistant often ends a message with a sentence like one of these:
- "I tested this and it works."
- "This compiles without errors."
- "All tests pass."
- "Verified on iPhone 15 simulator."
Unless the assistant has a tool that actually builds and runs your project, and shows you the output, these sentences are predictions written in the past tense. Even with a tool, "I ran it" is a claim until the output is in front of you.
What real evidence looks like
Real evidence is output you can read and recheck. Compare the two columns.
| A claim | Evidence you can check |
|---|---|
| "It builds." | The exact command, such as xcodebuild build ..., and its final line, which says the build succeeded or failed, plus the count of errors and warnings. |
| "Tests pass." | The test run output listing each test by name with a pass or fail, from a command like xcodebuild test. Per-test lines are what you want, not a single summary sentence. |
| "Works on iOS 17." | A run on an iOS 17 simulator, with the destination named in the command or the Xcode report. |
| "I checked it on a device." | A statement of which device. For anything involving haptics or the Home Screen icon, only a physical device or the right simulator can show it. |
Here is the shape of the output you are looking for. This is an illustrative sketch, not a real log from this project. The wording and format vary between Xcode versions.
Test case 'DiceRollerTests/rollUsesInjectedValues()' passed on 'iPhone 15'
Test case 'DiceRollerTests/rollTotalIncludesModifier()' passed on 'iPhone 15'
** TEST SUCCEEDED **
Notice what makes this checkable. It names each test, it names the destination, and it ends with a final status line you can search for. A message that says only "the tests pass" has none of those.
Rerun it yourself
The cheapest way to settle a claim is to produce the output on your own Mac.
- Open the project in Xcode and press ⌘B. Note any errors and warnings.
- Press ⌘U. Open the Test navigator and check that each expected test appears with a green mark.
- Press ⌘R on the simulator named in the claim, or on a different one. Perform the manual script for the feature.
- If a command-line result was quoted, copy the command and run it in Terminal from your project folder.
If your result differs from the claim, your result is the one that counts. Report it back to the assistant with the exact message, and say which Xcode and iOS version you used.
What to write down
When you accept a generated change, record what you did and did not verify. For example:
- Built with ⌘B on this date: yes or no, with the number of warnings.
- Tests with ⌘U: yes or no, which tests, which simulator.
- Ran manually: which steps.
- Not checked: for example, "not run on iOS 17", "not run on a physical device", "not run in Swift 6 mode".
The last line matters most. The course follows the same rule: it states what was verified and does not claim results it did not obtain.
A successful build shows the code is valid. A passing test shows one rule holds. Neither shows the screen looks right, the haptic fires, or the history survives a relaunch. Say which of those you actually checked.
Part 5 — A review checklist for pasted code
Use this list each time. It is ordered so the cheap checks come first.
- I committed my working project before pasting.
- I know which checkpoint this code is meant to extend, and the file layout and names match it.
git diffshows only the files and lines I expected.- I can say, in one sentence each, where execution starts, what the button calls, which values are state, and where data is saved.
- There are no new dependencies and no new layers I cannot justify.
- The project builds with ⌘B. I read the first error and the warnings.
- The deployment target is still iOS 17.0, and I did not raise it to remove an error.
- Every API I did not recognize was checked in quick help or Apple's documentation for its availability.
- The project's Swift language mode is unchanged, and I know whether it is 5 or 6.
- I did not accept
try!,!,as!,@unchecked Sendable, ornonisolated(unsafe)without understanding why. - If tests were added, they run with ⌘U, and I broke the code on purpose to see at least one fail.
- I ran the app and followed a manual script for the changed behavior, including a relaunch if anything is saved.
- I wrote down what I did not verify.
Part 6 — Troubleshooting generated code that fails
Work from symptom to cause
| Symptom | First thing to check |
|---|---|
| A wall of red errors after pasting | Read the first error only. Look for a missing or extra brace, or a pasted block that landed inside the wrong type. |
| "Cannot find ... in scope" | A name the assistant invented, or a file that exists in its version of the project and not in yours. Search your project for the name. |
| "Value of type ... has no member ..." | The assistant assumed a property or method your type does not have. Open your type and compare. |
| An availability error mentioning a newer iOS | The API is newer than your deployment target. Choose another approach or use #available. See Check 3. |
A concurrency error such as one about main actor isolation or Sendable |
Check the language mode first, then the default actor isolation. See Check 4. |
| "Cannot assign to property: 'self' is immutable" | A value that changes is not marked @State or is held in a let. Chapter 12 shows this one. |
| The build succeeds but the screen does not update | The value that changes is not state, or a copy of it is being changed. Trace where it is set. |
| Rolls work but history is empty after relaunch | A save step is missing or an error is being swallowed by try?. Chapter 9 and Chapter 12 cover this. |
| Preview crashes but the app runs | The preview needs sample data or an environment value it does not have. Run the app to see whether the code is actually wrong. |
| Tests do not appear in the Test navigator | The file is not in the test target, or it uses a framework your target is not set up for. |
Give the assistant what it needs
A vague report gets a vague fix. When you go back to an assistant, include:
- The exact error text and the file and line.
- Your Xcode version, deployment target, and Swift language mode.
- The relevant code, not only a description of it.
- What you expected and what happened instead.
- A constraint: "make the smallest change", "do not add files", "keep iOS 17.0".
Give the model the facts of your environment so it does not guess.
A useful request is: "Explain what each line of this change does and which lines are new compared with my version." Then check the explanation against the code yourself. If the explanation names something that is not in the code, or describes a behavior the code does not produce, you have found a problem before it reached your app.
When to stop and start over
Sometimes a series of generated fixes makes the project worse: each fix adds a line to quiet one error and creates another. Stop when you notice the same area being patched three times. Discard the changes with Git, return to your last commit, and restate the request with what you learned. You can also compare your files with the reference checkpoint for your chapter. Chapter 12 and Chapter 13's development checkpoints show how to compare folders.
Summary
- Anchor generated code to a checkpoint you already understand.
- Read it with the course's questions: where it starts, what the button does, what is state, where data is saved.
- Check the build, the deployment target, API availability, the language mode, and the tests, in that order.
- Treat "it compiles" and "tests pass" as claims until you see the command and the output, and rerun them yourself.
- Record what you did not verify.