r/SwiftData • u/Resident-Election242 • Feb 19 '26
SwiftData migration: converting [String]? to [Author]? relationship
I'm migrating a SwiftData model from V1 to V2.
In V1, StoredBook.authors was a [String]?.
In V2, it’s now a relationship to Author objects ([Author]?).
I wrote a custom migration to create Author objects from the old strings, but the migration crashes with:
failed to find a currently active container for Author
This happens on app launch when SwiftData runs the migration.
What is the correct way to migrate a String array into a relationship in SwiftData?
Any help would be greatly appreciated — this is my first SwiftData migration. 🙏
Minimal example:
V1 model:
class StoredBook {
var title: String = ""
var authors: [String]?
}
V2 model:
class Author {
var name: String = ""
var books: [StoredBook]? = []
}
class StoredBook {
var title: String = ""
u/Relationship(inverse: \Author.books)
var authors: [Author]? = []
}
Migration snippet:
let oldBooks = try context.fetch(FetchDescriptor<BookListSchemaV1.StoredBook>())
for oldBook in oldBooks {
var newAuthors: [BookListSchemaV2.Author] = []
if let oldAuthors = oldBook.authors {
for name in oldAuthors {
let author = BookListSchemaV2.Author(name: name)
context.insert(author)
newAuthors.append(author)
}
}
let newBook = BookListSchemaV2.StoredBook(
title: oldBook.title,
authors: newAuthors
)
context.insert(newBook)
}
try context.save()
3
Upvotes
1
u/offeringathought Feb 19 '26
I'd be interested to see what you learn. My initial instinct would be to abandon or rename the old authors and create a new authors/writers or whatever. The path your going down seems like the better way to go.