如何使用Swift在Realm中保存多维数组并支持增删操作
Hey there! Sorry you’ve been stuck on this for a week—let’s break this down simply. Realm doesn’t support storing multidimensional arrays directly, but we can work around this by wrapping each sub-array in a Realm object. Here’s a step-by-step solution:
1. Define Realm Object Classes
First, we’ll create two Realm Object subclasses: one to represent each sub-array, and another to hold the entire sequence of sub-arrays.
import RealmSwift // This class wraps a single sub-array (e.g., [0, 1] or [0, 2, 1]) class SubSequence: Object { // Store the elements of the sub-array in a Realm List let elements = List<Int>() // Convenience initializer to convert a regular [Int] to a SubSequence convenience init(from array: [Int]) { self.init() elements.append(objectsIn: array) } } // This class holds the entire sequence of sub-arrays class SequenceContainer: Object { // Store all SubSequence objects in a Realm List let sequences = List<SubSequence>() // Optional: Add an ID if you need to reference this container later @Persisted(primaryKey: true) var id: UUID = UUID() // Convenience initializer to convert your initial [[Int]] array convenience init(from sequenceArray: [[Int]]) { self.init() sequenceArray.forEach { subArray in sequences.append(SubSequence(from: subArray)) } } }
2. Save Your Initial Sequence to Realm
Now you can take your existing [[Int]] array and save it to Realm using the container class:
let realm = try! Realm() // Your initial sequence let initialSequence = [[0, 1], [0, 2, 1], [4, 5, 1]] // Create a container and save it to Realm try! realm.write { let container = SequenceContainer(from: initialSequence) realm.add(container) }
3. Add a New Sub-Array
To add a new sub-array to your stored sequence, fetch the container and append a new SubSequence object:
// Fetch the container (assuming you're using the ID to find it) guard let container = realm.objects(SequenceContainer.self).first else { print("No sequence container found!") return } // New sub-array to add let newSubArray = [3, 0, 2] try! realm.write { container.sequences.append(SubSequence(from: newSubArray)) }
4. Delete a Sub-Array
To remove a sub-array, you can target it by index or by its contents:
Delete by Index
try! realm.write { // Delete the 2nd sub-array (index 1, since arrays are 0-indexed) container.sequences.remove(at: 1) }
Delete by Contents
If you want to delete a sub-array that matches a specific [Int] value:
let targetSubArray = [0, 1] // Find the SubSequence that matches the target array if let targetSequence = container.sequences.first(where: { $0.elements.map { $0 } == targetSubArray }) { try! realm.write { container.sequences.remove(object: targetSequence) } }
5. Modify Elements in a Sub-Array
You can also update individual elements within a sub-array:
// Get the first sub-array guard let firstSubSequence = container.sequences.first else { return } try! realm.write { // Change the first element from 0 to 9 firstSubSequence.elements[0] = 9 }
Key Notes
- Realm works best with object-oriented structures, so wrapping sub-arrays in
SubSequenceobjects lets us leverage Realm’s built-in support forListcollections. - Always make sure to perform write operations inside a
realm.writeblock—this ensures changes are persisted safely.
内容的提问来源于stack exchange,提问作者Dav Irv

