Finding answers to questions in a text document
At a glance
| Item | Summary |
|---|---|
| Purpose | Locate relevant passages in a document by asking the Bidirectional Encoder Representations from Transformers (BERT) model a question. |
| App architecture | A storyboard UISplitViewController app. MainViewController lists Document values; DetailViewController shows one document, owns a BERT wrapper, and runs a question on a background queue. The Model/ folder turns text into BERT input (TokenizedString, BERTVocabulary, BERTInput), runs the Xcode-generated BERTQAFP16 model class, and decodes the start and end logits back into a Substring of the document. |
| Main patterns | Master-detail view controllers over a separate model layer; UIKit delegate and data-source callbacks. |
| Project style | FindingAnswers/ split into App/ (delegates, storyboard, Info.plist), View/ (controllers and Document), and Model/ (BERT pipeline, .mlmodel, vocabulary file). |
| Execution model | GCD only: one DispatchQueue.global(qos: .userInitiated).async for the prediction and a DispatchQueue.main.async hop to update the UI. No Swift concurrency. |
| State/event model | Document value copied into the detail controller; detailItem didSet refreshes the view; keyboard notifications adjust a layout constraint. |
| Key frameworks/packages | CoreML, NaturalLanguage (NLTagger word tokenization), UIKit. The project declares no Swift package. |
Project structure
FindingAnswers.xcodeproj/ one app target, iPhone/iPad + Mac Catalyst
FindingAnswers/
├── App/
│ ├── AppDelegate.swift scene configuration
│ ├── SceneDelegate.swift UISplitViewControllerDelegate (collapse rule)
│ └── Base.lproj/Main.storyboard split view, table, detail
├── View/
│ ├── MainViewController.swift document list, segue action
│ ├── DetailViewController.swift document text, question field, BERT search
│ └── Document.swift struct Document: Codable
└── Model/
├── BERT.swift findAnswer(for:in:)
├── BERTInput.swift token IDs, token types, MLMultiArray input
├── BERTOutput.swift logits to best start/end indices
├── BERTVocabulary.swift vocabulary file to [Substring: Int]
├── TokenizedString.swift NLTagger words, then wordpieces
├── BERTQAFP16.mlmodel compiled into a generated model class
└── bert-base-uncased-vocab.txt
Structure observations
- The model file is a Sources-phase member, so Xcode generates the
BERTQAFP16,BERTQAFP16Input, andBERTQAFP16Outputtypes that the Swift files use (FindingAnswers.xcodeproj/project.pbxproj:14,FindingAnswers/Model/BERT.swift:12). View/contains no Core ML code except theBERTproperty and thefindAnswercall inDetailViewController(FindingAnswers/View/DetailViewController.swift:17,FindingAnswers/View/DetailViewController.swift:69). All tokenization and logit decoding live inModel/.- The app target enables Mac Catalyst and builds for iPhone and iPad (
FindingAnswers.xcodeproj/project.pbxproj:421,FindingAnswers.xcodeproj/project.pbxproj:423), matching the DocC platform list. - The Info.plist scene configuration loads
Main.storyboardforSceneDelegate(FindingAnswers/App/Info.plist:36).
Overall architecture
flowchart LR
Split["UISplitViewController (storyboard)"] --> Main["MainViewController"]
Split --> Detail["DetailViewController"]
Main -- "@IBSegueAction: detailItem" --> Detail
Detail --> BERT["BERT.findAnswer"]
BERT --> Input["BERTInput"]
Input --> Tok["TokenizedString + BERTVocabulary"]
BERT --> Model["BERTQAFP16 (generated)"]
BERT --> Output["bestLogitsIndices"]
Detail -- "answer Substring" --> Highlight["attributed text highlight"]
Reference code
FindingAnswers/Model/BERT.swift:28 — the end-to-end question-answering pipeline
func findAnswer(for question: String, in document: String) -> Substring {
// Prepare the input for the BERT model.
let bertInput = BERTInput(documentString: document, questionString: question)
guard bertInput.totalTokenSize <= BERTInput.maxTokens else {
// ...
}
// The MLFeatureProvider that supplies the BERT model with its input MLMultiArrays.
let modelInput = bertInput.modelInput!
// Make a prediction with the BERT model.
guard let prediction = try? bertModel.prediction(input: modelInput) else {
return "The BERT model is unable to make a prediction."
}
// ...
// Return the portion of the original string as the answer.
let originalText = bertInput.document.original
return originalText[answerStart..<answerEnd]
}Interpretation
Observed: findAnswer returns a Substring of the original document. Error cases also return a Substring, built from a message string. DetailViewController tells the two apart by checking answer.base == detail.body before highlighting (FindingAnswers/View/DetailViewController.swift:73). Because the token substrings come from the original string, the answer’s indices map straight back to UTF-16 offsets for NSRange (FindingAnswers/View/DetailViewController.swift:83).
Inference: returning a slice instead of a copied string is what lets the UI highlight the exact span without searching for the answer text again.
Ownership and state
classDiagram
MainViewController *-- Document : objects array
MainViewController --> DetailViewController : sets detailItem in segue action
DetailViewController *-- BERT : let bert
DetailViewController *-- Document : detailItem copy
BERT ..> BERTQAFP16 : new instance per access
BERT ..> BERTInput : per call
BERTInput *-- TokenizedString : question, document
BERTVocabulary *-- Dictionary : private static lookupDictionary
SceneDelegate --> UISplitViewController : delegate
Ownership evidence
FindingAnswers/Model/BERT.swift:12 — the model is a computed property, not a stored one
class BERT {
/// The underlying Core ML Model.
var bertModel: BERTQAFP16 {
do {
let defaultConfig = MLModelConfiguration()
return try BERTQAFP16(configuration: defaultConfig)
} catch {
fatalError("Couldn't load BERT model due to: \(error.localizedDescription)")
}
}
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
MainViewController |
objects: [Document] |
Stored array, seeded with one example (FindingAnswers/View/MainViewController.swift:14) |
MainViewController inserts and deletes rows |
MainViewController |
Detail navigation controller | Creates it in @IBSegueAction and assigns detailItem (FindingAnswers/View/MainViewController.swift:48, FindingAnswers/View/MainViewController.swift:64) |
Storyboard segue machinery presents it |
DetailViewController |
detailItem: Document? |
A value copy; didSet calls configureView() (FindingAnswers/View/DetailViewController.swift:46) |
DetailViewController, including on text-view edits (FindingAnswers/View/DetailViewController.swift:107) |
DetailViewController |
bert |
Creates and retains one BERT per detail controller (FindingAnswers/View/DetailViewController.swift:17) |
Immutable let |
BERT |
BERTQAFP16 model |
Created on every read of bertModel; not cached |
No stored state |
BERTVocabulary |
lookupDictionary |
private static let, loaded once from the bundle (FindingAnswers/Model/BERTVocabulary.swift:37) |
Immutable after load |
SceneDelegate |
Split view delegate | Sets itself as the delegate when the scene connects (FindingAnswers/App/SceneDelegate.swift:19) |
UIKit owns the split view |
Observed: because Document is a struct, edits saved in textViewDidEndEditing(_:) update only the detail controller’s copy; nothing writes them back to MainViewController.objects. MainViewController.detailViewController is assigned from split.viewControllers.last as? DetailViewController (FindingAnswers/View/MainViewController.swift:27) and never read afterward. Inference: in this storyboard the last split child is a navigation controller, so that cast likely produces nil.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Background prediction | DispatchQueue.global(qos: .userInitiated).async |
Tokenization, model load, prediction, and logit decoding all run inside one global-queue work item | FindingAnswers/View/DetailViewController.swift:67, FindingAnswers/View/DetailViewController.swift:69 |
| Return to main queue | DispatchQueue.main.async |
Highlighting, textField.text, and the placeholder are restored on the main queue |
FindingAnswers/View/DetailViewController.swift:72 |
| Captured state | The work item captures self, the detail value, and searchText |
The document is copied before the hop, so later edits do not change the running search | FindingAnswers/View/DetailViewController.swift:56, FindingAnswers/View/DetailViewController.swift:61 |
| Shared read-only state | private static let lookupDictionary |
Swift initializes a global or static let once on first access; afterward the dictionary is only read |
FindingAnswers/Model/BERTVocabulary.swift:37 |
| Overlapping searches | None | Nothing prevents a second search from starting while one runs; each gets its own model instance because bertModel is computed |
FindingAnswers/Model/BERT.swift:43 |
| Keyboard notifications | NotificationCenter.addObserver in viewWillAppear, removeObserver in viewWillDisappear |
Observers are added and removed as a pair | FindingAnswers/View/DetailViewController.swift:114, FindingAnswers/View/DetailViewController.swift:127 |
Reference code
FindingAnswers/View/DetailViewController.swift:67 — background search, main-queue UI update
DispatchQueue.global(qos: .userInitiated).async {
// Use the BERT model to search for the answer.
let answer = self.bert.findAnswer(for: searchText, in: detail.body)
// Update the UI on the main queue.
DispatchQueue.main.async {
if answer.base == detail.body, let textView = self.documentTextView {
// ...
textView.attributedText = mutableAttributedText
}
textField.text = String(answer)
textField.placeholder = placeholder
}
}Observed: the background work item touches no controller state except the immutable bert reference; every UIKit write is inside the main-queue block. The source does not cancel an in-flight search.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| List to detail | @IBSegueAction makeDetailViewController(coder:sender:segueIdentifier:) |
Builds the destination and injects the selected Document |
FindingAnswers/View/MainViewController.swift:48 |
| View refresh | detailItem didSet → configureView() |
Any assignment redraws the title and text | FindingAnswers/View/DetailViewController.swift:47 |
| Delegate callbacks | UITextFieldDelegate, UITextViewDelegate, UISplitViewControllerDelegate, table data source |
Search on Return, reset on Clear, save edits, collapse rule | FindingAnswers/View/DetailViewController.swift:54, FindingAnswers/App/SceneDelegate.swift:24, FindingAnswers/View/MainViewController.swift:71 |
| Model I/O | MLMultiArray, generated BERTQAFP16Input/Output |
Token IDs and types in; startLogits/endLogits out |
FindingAnswers/Model/BERTInput.swift:84, FindingAnswers/Model/BERTOutput.swift:47 |
| Framework import | CoreML |
Model wrapper, input, and output helpers | FindingAnswers/Model/BERT.swift:8 |
| Framework import | NaturalLanguage |
NLTagger word tokenization |
FindingAnswers/Model/TokenizedString.swift:8, FindingAnswers/Model/TokenizedString.swift:47 |
| Framework import | UIKit, CoreML |
Detail controller | FindingAnswers/View/DetailViewController.swift:8 |
| Package declaration | None | The project file declares no Swift package | FindingAnswers.xcodeproj/project.pbxproj:422 |
Class and protocol design
classDiagram
class BERT {
bertModel
findAnswer(question, document)
bestLogitsIndices(prediction, range)
}
class BERTInput {
<<struct>>
maxTokens = 384
modelInput
documentRange
}
class TokenizedString {
<<struct>>
original
tokens
tokenIDs
}
class BERTVocabulary {
<<struct>>
tokenID(of)
}
BERT --> BERTInput
BERTInput --> TokenizedString
TokenizedString --> BERTVocabulary
Reference code
FindingAnswers/Model/BERTInput.swift:10 — input limits and the document’s position in the token sequence
struct BERTInput {
/// The maximum number of tokens the BERT model can process.
static let maxTokens = 384
// There are 2 sentinel tokens before the document, 1 [CLS] token and 1 [SEP] token.
static private let documentTokenOverhead = 2
// There are 3 sentinel tokens total, 1 [CLS] token and 2 [SEP] tokens.
static private let totalTokenOverhead = 3
var modelInput: BERTQAFP16Input?
let question: TokenizedString
let document: TokenizedString
private let documentOffset: Int
var documentRange: Range<Int> {
return documentOffset..<documentOffset + document.tokens.count
}
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
BERT |
Orchestrates input, prediction, and decoding; returns a Substring |
BERTInput, BERTQAFP16, BERTOutput.swift extension |
BERTInput |
Builds [CLS] question [SEP] document [SEP] [PAD]... IDs and 0/1 token types as MLMultiArrays |
TokenizedString, BERTVocabulary |
TokenizedString |
NLTagger word split, then greedy longest-prefix wordpiece split with ## suffixes |
NaturalLanguage, BERTVocabulary |
BERTVocabulary |
Loads and validates the 30,522-entry vocabulary; maps tokens to IDs | Bundle resource |
BERTOutput.swift extensions |
Top-20 start and end logits, best pair with end >= start |
MLMultiArray, Array |
MainViewController, DetailViewController |
List and detail UI | Document, BERT |
Observed: the sample defines no protocols. The model layer uses value types plus a single BERT class, and the generated Core ML classes form the framework boundary.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
BERTVocabulary.init(), lookupDictionary, loadVocabulary() (FindingAnswers/Model/BERTVocabulary.swift:36, FindingAnswers/Model/BERTVocabulary.swift:43) |
private |
The type cannot be instantiated; callers use only the static tokenID(of:) methods and token constants |
Inference: a namespace with one lazily loaded table. |
TokenizedString._tokens, _tokenIDs, tokenize, wordTokens, wordpieceTokens (FindingAnswers/Model/TokenizedString.swift:11, FindingAnswers/Model/TokenizedString.swift:31) |
private |
Tokens can be read only through tokens and tokenIDs |
Inference: keeps the two arrays in sync after initialization. |
TokenizedString.tokens, tokenIDs (FindingAnswers/Model/TokenizedString.swift:15) |
public on an implicitly internal struct |
Effective visibility is still internal, because a member cannot be more visible than its type |
The public keyword has no effect beyond the module here. |
BERTInput.documentTokenOverhead, totalTokenOverhead, documentOffset (FindingAnswers/Model/BERTInput.swift:15, FindingAnswers/Model/BERTInput.swift:25) |
static private / private |
Sentinel arithmetic is hidden; callers see documentRange and totalTokenSize |
Inference: one place encodes the token layout. |
MainViewController.exampleText (FindingAnswers/View/MainViewController.swift:11) |
static private |
Seed text is local to the list controller | Inference: sample data. |
DetailViewController.questionTextFieldSpacing (FindingAnswers/View/DetailViewController.swift:143) |
private |
Layout constant is local | Inference: implementation detail. |
BERT.bertModel, findAnswer, bestLogitsIndices (FindingAnswers/Model/BERT.swift:12, FindingAnswers/Model/BERTOutput.swift:45) |
implicit internal |
Any type in the module can read the model or call the helpers | Inference: one-module sample. |
Reference code
FindingAnswers/Model/TokenizedString.swift:10 — private storage with read-only accessors
struct TokenizedString {
private let _tokens: [Substring]
private let _tokenIDs: [Int]
let original: String
public var tokens: [Substring] { return _tokens }
public var tokenIDs: [Int] { return _tokenIDs }
// ...
}The private boundaries are concentrated in the model layer. The view controllers rely on Swift’s implicit internal.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Word tokenization | TokenizedString.wordTokens(from:) |
NLTagger with .word units and .omitWhitespace (FindingAnswers/Model/TokenizedString.swift:42). |
| Wordpiece splitting | TokenizedString.wordpieceTokens(from:) |
Shortens each word from the end until a vocabulary hit, then repeats with ## on the remainder (FindingAnswers/Model/TokenizedString.swift:68). |
| Token limit | BERTInput.init and BERT.findAnswer |
BERTInput builds modelInput only when totalTokenSize < maxTokens (FindingAnswers/Model/BERTInput.swift:43), while findAnswer proceeds when totalTokenSize <= maxTokens and force-unwraps modelInput (FindingAnswers/Model/BERT.swift:32, FindingAnswers/Model/BERT.swift:40). Observed: an input of exactly 384 tokens passes the second check but not the first. |
| Answer span | BERT.bestLogitsIndices(from:in:) and findBestLogitPair |
Restricts logits to the document range, keeps the top 20 of each, and picks the highest start-plus-end sum with end >= start (FindingAnswers/Model/BERTOutput.swift:55, FindingAnswers/Model/BERTOutput.swift:89). |
| Highlighting | DetailViewController.textFieldShouldReturn(_:) |
Dims the whole text, then restores full color on the answer range (FindingAnswers/View/DetailViewController.swift:79). |
| Keyboard avoidance | DetailViewController.animateBottomLayoutConstraint(from:) |
Sets an absolute constraint value from the keyboard overlap minus the safe-area inset (FindingAnswers/View/DetailViewController.swift:188). |
| Split collapse | SceneDelegate.splitViewController(_:collapseSecondary:onto:) |
Collapses only when the detail has no document (FindingAnswers/App/SceneDelegate.swift:35). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | Storyboard master-detail: MainViewController injects a Document into DetailViewController through @IBSegueAction (FindingAnswers/View/MainViewController.swift:64); DetailViewController calls into the separate Model/ layer (FindingAnswers/View/DetailViewController.swift:69) |
Controllers handle UI and threading; the model layer is UIKit-free. |
| Delegate or data-source callbacks | UITextFieldDelegate/UITextViewDelegate on DetailViewController (FindingAnswers/View/DetailViewController.swift:11), UISplitViewControllerDelegate on SceneDelegate (FindingAnswers/App/SceneDelegate.swift:10), table data source on MainViewController |
User and container events reach the controllers through UIKit protocols. |
Naming conventions
- Model types share a
BERTprefix that names the model family (BERT,BERTInput,BERTVocabulary); the generated class isBERTQAFP16, after the.mlmodelfile. FileBERTOutput.swiftholds extensions rather than aBERTOutputtype. - Methods read as questions or transformations:
findAnswer(for:in:),bestLogitsIndices(from:in:),indicesOfLargest(_:),tokenID(of:). - Private storage uses a leading underscore (
_tokens,_tokenIDs) behind same-named computed accessors. - The vocabulary constant is spelled
unkownTokenIDin source.
Architecture takeaways
- Keep the ML pipeline UIKit-free and value-typed: tokenize, build input, predict, decode, then return a slice of the original text so the UI can map it back to a range.
- Put fixed token-layout arithmetic (sentinels, offsets, padding) in one private place, and expose only derived values such as
documentRange. - One background work item per request, with a main-queue hop for UI, is enough for a single synchronous Core ML prediction.
- A computed model property reloads the
MLModelon every prediction. Inference: storing the instance would avoid repeated loading; the source does not do so. - Check limits consistently: the
<versus<=mismatch aroundmaxTokensshows why one source of truth for a constraint matters.
Source map
| Source file | Relevant symbols |
|---|---|
FindingAnswers/Model/BERT.swift |
BERT, bertModel, findAnswer(for:in:) |
FindingAnswers/Model/BERTInput.swift |
BERTInput, maxTokens, documentRange, init(documentString:questionString:) |
FindingAnswers/Model/BERTOutput.swift |
indicesOfLargest(_:), doubleArray(), bestLogitsIndices(from:in:), findBestLogitPair |
FindingAnswers/Model/BERTVocabulary.swift |
BERTVocabulary, lookupDictionary, loadVocabulary() |
FindingAnswers/Model/TokenizedString.swift |
TokenizedString, wordTokens(from:), wordpieceTokens(from:) |
FindingAnswers/View/DetailViewController.swift |
DetailViewController, bert, detailItem, textFieldShouldReturn(_:) |
FindingAnswers/View/MainViewController.swift |
MainViewController, objects, makeDetailViewController(coder:sender:segueIdentifier:) |
FindingAnswers/App/SceneDelegate.swift |
SceneDelegate, split-view collapse |
FindingAnswers/App/Info.plist |
Scene manifest |
FindingAnswers.xcodeproj/project.pbxproj |
Model source membership, Mac Catalyst, device family |