# Why does a SwiftData Model allow Array? How do you really store one?

**URL:** <https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257>\
**Category:** Using Swift\
**Tags:** swiftdata\
**Created:** [July 19, 2023, 8:51pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257 "2023-07-19T20:51:41Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [July 19, 2023, 8:51pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/1 "2023-07-19T20:51:41Z")

</div>

Order is not preserved, meaning the `Array` that exists in memory is not likely the one that will get persisted and reloaded. That's not really conceptually an `Array`—that's halfway to a `Set`.

I'm not seeing a general purpose solution on the Apple Developer Forums yet, and I haven't thought of one myself yet. Have you?

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [July 20, 2023, 12:42am UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/2 "2023-07-20T00:42:44Z")

</div>

> [@anon9791410](#):
>
> Order is not preserved, meaning the `Array` that exists in memory is not likely the one that will get persisted and reloaded. That's not really conceptually an `Array`—that's halfway to a `Set`.

What?! Please show a reproducible snippet.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [July 20, 2023, 2:16pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/4 "2023-07-20T14:16:25Z")

</div>

```swift
let items = try! modelContext.fetch(FetchDescriptor<T>(sortBy: []))

```

This returns "array" items in arbitrary order, unless you specify a sort descriptor.

> [@anon9791410](#):
>
> Today I'm having the idea that a linked list of models may be the way to go…?

Doubly linked list if you need to remove arbitrary items?

* * *

_Edit:_

Wait, if you don't need O(1) lookup behaviour for your "arrays" (how else could you tolerate having a list?) maybe you just sort your items by a string ID as in vocabulary:

E.g. you have two items: `A Z`  
When inserting third that would become: `A M Z`  
If you have this list: `A B ... Z`  
and need to insert an item between A and B then it becomes: `A AM B Z`

and so on.

And the key (ID) could be not a string but a more optimal data structure, e.g. an array of UInt8.

On the second thought, doubly linked list with fixed sized ID could be more efficient.

---

<div class="post-metadata">

**Author:** ![rarematter](https://avatars.discourse-cdn.com/v4/letter/r/a5b964/32.png) [@rarematter](https://forums.swift.org/u/rarematter)\
**Post date:** [July 23, 2023, 6:40pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/6 "2023-07-23T18:40:32Z")

</div>

I've just discovered this issue today while seeing my SwiftUI lists reorder randomly, after attempting to insert a new item at the front of a model "stored" array.

I haven't seen any indication from the docs or API that this is intended behavior from SwiftData. Yet, this is noticeably absent as a known issue from the Xcode beta release notes. See here: [SwiftData Known Issues](https://developer.apple.com/documentation/xcode-release-notes/xcode-15-release-notes#Known-Issues)

User-decided ordering is critical for my use-case, so I'll be trying out some workarounds until Apple (hopefully) fixes this before release.

In the meantime, I'll be sending a bug report. The more the merrier!

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [July 25, 2023, 2:11am UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/7 "2023-07-25T02:11:01Z")

</div>

> [@tera](#):
>
> Wait, if you don't need O(1) lookup behaviour for your "arrays" (how else could you tolerate having a list?) maybe you just sort your items by a string ID as in vocabulary:
> 
> E.g. you have two items: `A Z`  
> When inserting third that would become: `A M Z`  
> If you have this list: `A B ... Z`  
> and need to insert an item between A and B then it becomes: `A AM B Z`
> 
> and so on.
> 
> And the key (ID) could be not a string but a more optimal data structure, e.g. an array of UInt8.

Giving this idea a test:

[details="SwiftData's array "vocabulary" storage"]

```swift
import SwiftUI
import SwiftData

@Model final class Card {
    var id: String?
    var key: Double

    init(id: String, key: Double) {
        self.id = id
        self.key = key
    }
}
 
struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \.key, order: .forward) var cards: [Card]
    @State var selectedID: String?
    
    var body: some View {
        NavigationView {
            List {
                ForEach(cards) { card in
                    HStack {
                        Text(card.id ?? "")
                        Spacer()
                        Text(String(card.key)).font(.subheadline).foregroundColor(.secondary)
                    }.background(card.id == selectedID ? Color.red : Color.clear)
                }
            }
            .toolbar {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    Button("+10") {
                        withAnimation {
                            for i in 0 ..< 10 {
                                let newCard = Card(
                                    id: String(i),
                                    key: Double(i)
                                )
                                modelContext.insert(newCard)
                            }
                        }
                    }
                    Button {
                        withAnimation {
                            if !cards.isEmpty {
                                // delete random card
                                let i = Int.random(in: 0 ..< cards.count)
                                modelContext.delete(cards[i])
                                selectedID = cards[i].id
                            }
                        }
                    } label: {
                        Image(systemName: "minus")
                    }
                    .disabled(cards.isEmpty)
                    
                    Button {
                        withAnimation {
                            // insert a new card in a random position
                            let count = cards.count
                            let i = count == 0 ? 0 : Int.random(in: 0 ..< count)
                            let prev = count == 0 ? 0 : cards[i].key
                            let next = i + 1 < count ? cards[i + 1].key : prev + 1
                            let newKey = (prev + next)/2
                            let newID = "\(newKey)"
                            selectedID = newID
                            
                            modelContext.insert(
                                Card(
                                    id: "\(newKey)",
                                    key: newKey
                                )
                            )
                        }
                    } label: {
                        Image(systemName: "plus")
                    }
                }
            }
        }
    }
}

@main struct CardsApp: App {
    var body: some Scene {
        WindowGroup { ContentView() }
        .modelContainer(for: [Card.self])
    }
}

```

[/details]

I'm using a double key for simplicity just to test the idea. In real app that uses this strategy the key must be variable length (array of UInt8 will do).

> [@tera](#):
>
> On the second thought, doubly linked list with fixed sized ID could be more efficient.

On this one I am not sure how to proceed with the query to return items in the list order.

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [July 25, 2023, 7:53pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/8 "2023-07-25T19:53:34Z")

</div>

SwiftData, like SwiftUI, is an Apple platform framework, and questions that are just about using the framework should be asked over at the [Apple developer forums](https://forums.developer.apple.com/).

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [July 25, 2023, 7:53pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/9 "2023-07-25T19:53:40Z")

</div>

Unlisted on July 25, 2023, 7:53pm UTC



---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [July 25, 2023, 9:44pm UTC](https://forums.swift.org/t/why-does-a-swiftdata-model-allow-array-how-do-you-really-store-one/66257/11 "2023-07-25T21:44:41Z")

</div>

I know, but it’s still off-topic here even if you didn’t get a response there.
