### Install via Swift Package Manager Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Add the identified collections package dependency to your Package.swift file and link the product to your target. ```swift // Package.swift dependencies: [ .package( url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0" ) ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "IdentifiedCollections", package: "swift-identified-collections") ] ) ] ``` -------------------------------- ### Access All Identifiers in O(1) Time Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Use the `ids` property to get an `OrderedSet` of all element identifiers. This allows for fast membership tests and set operations without iterating through the elements. ```swift import IdentifiedCollections import OrderedCollections let users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] let ids: OrderedSet = users.ids print(ids) // ["u_1", "u_2"] print(ids.contains("u_2")) // true // Fast membership check without scanning elements let incomingIDs: Set = ["u_2", "u_3"] let newIDs = incomingIDs.subtracting(ids) print(newIDs) // ["u_3"] ``` -------------------------------- ### Get Array View of Elements in O(1) Time Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt The `elements` property provides a plain `[Element]` array in O(1) time. This is useful when you need to pass elements to APIs that specifically require an `Array` type. ```swift import IdentifiedCollections let users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] let plainArray: [User] = users.elements print(type(of: plainArray)) // Array // Encode as a plain JSON array let data = try JSONEncoder().encode(users) // ["u_1" entry, "u_2" entry] let decoded = try JSONDecoder().decode(IdentifiedArrayOf.self, from: data) print(decoded == users) // true ``` -------------------------------- ### IdentifiedArray Initialization with Custom Key Path Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Shows how to initialize IdentifiedArray using a key path to a Hashable property for custom identity, similar to SwiftUI's List and ForEach. ```APIDOC ## IdentifiedArray(id:) — Custom Key Path Identity `IdentifiedArray` does not require elements to conform to `Identifiable`. Any key path to a `Hashable` property can serve as the identifier, mirroring SwiftUI's `List(_, id:)` and `ForEach(_, id:)` APIs. ```swift import IdentifiedCollections struct Product { var sku: String var name: String var price: Double } // Use `\.sku` as the identity key path var inventory = IdentifiedArray(id: \Product.sku) inventory.append(Product(sku: "ABC-001", name: "Widget", price: 9.99)) inventory.append(Product(sku: "ABC-002", name: "Gadget", price: 19.99)) // Self-identity for value types like Int or String var numbers = IdentifiedArray(id: \Int.self) numbers.append(contentsOf: [1, 2, 3, 4, 5]) print(numbers[id: 3]) // Optional(3) ``` ``` -------------------------------- ### IdentifiedArrayOf Initialization Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Demonstrates how to initialize IdentifiedArrayOf from array literals or existing sequences, and how to create an empty collection. ```APIDOC ## IdentifiedArrayOf — Declaring an Identified Collection `IdentifiedArrayOf` is a type alias for `IdentifiedArray` available when `Element` conforms to `Identifiable`. It is the primary type used in practice and can be initialized from an array literal or an existing sequence just like a standard `Array`. ```swift import IdentifiedCollections struct Todo: Identifiable, Equatable { let id: UUID var title: String var isComplete: Bool } // Literal initialization — identical to [Todo] syntax var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Buy groceries", isComplete: false), Todo(id: UUID(), title: "Call Mom", isComplete: false), ] // From an existing sequence let fetched: [Todo] = fetchTodosFromServer() var todosFromServer = IdentifiedArrayOf(uniqueElements: fetched) // Empty initialization var empty: IdentifiedArrayOf = [] print(empty.count) // 0 ``` ``` -------------------------------- ### SwiftUI List Rendering Todos Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Demonstrates how to render a list of `Todo` items in SwiftUI using an `ObservedObject` view model. The `List` automatically uses the `id` property for identification. ```swift struct TodosView: View { @ObservedObject var viewModel: TodosViewModel var body: some View { List(self.viewModel.todos) { todo in ... } } } ``` -------------------------------- ### Handle Errors in Swift Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md This snippet demonstrates basic error handling in Swift using a do-catch block. Ensure proper error types are defined and thrown for effective handling. ```swift } catch { // Handle error } } } ``` -------------------------------- ### Safe Asynchronous Update Using Todo ID Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Demonstrates the correct pattern for handling asynchronous updates to a collection item. It involves capturing the item's stable `id` before the async operation and then re-finding the item's index after the operation completes. ```swift class TodosViewModel: ObservableObject { ... func todoCheckboxToggled(at index: Int) async { self.todos[index].isComplete.toggle() // 1️⃣ Get a reference to the todo's id before kicking off the async work let id = self.todos[index].id do { // 2️⃣ Update the todo on the backend let updatedTodo = try await self.apiClient.updateTodo(self.todos[index]) // 3️⃣ Find the updated index of the todo after the async work is done let updatedIndex = self.todos.firstIndex(where: { $0.id == id })! // 4️⃣ Update the correct todo self.todos[updatedIndex] = updatedTodo } catch { // Handle error } } } ``` -------------------------------- ### Safe and Deduplicating Initializers for IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Use `init(uniqueElements:)` for a safe initializer that traps on duplicate IDs. Use `init(_:id:uniquingIDsWith:)` to accept duplicates and resolve them with a combining closure, useful for merging data from untrusted sources. ```swift import IdentifiedCollections struct Item: Identifiable { let id: Int var value: String } // Safe: traps if source contains duplicates let unique = IdentifiedArrayOf([ Item(id: 1, value: "a"), Item(id: 2, value: "b"), ]) // Deduplicating: keep the latest item for each id let raw = [Item(id: 1, value: "old"), Item(id: 2, value: "b"), Item(id: 1, value: "new")] let merged = IdentifiedArrayOf(raw, uniquingIDsWith: { _, new in new }) print(merged[id: 1]?.value) // Optional("new") // Deduplicating with key path identity for non-Identifiable types struct Record { var key: String var payload: String } let records = [ Record(key: "x", payload: "first"), Record(key: "x", payload: "second"), ] let deduped = IdentifiedArray(records, id: \.key, uniquingIDsWith: { _, latest in latest }) print(deduped[id: "x"]?.payload) // Optional("second") ``` -------------------------------- ### sort(by:), sorted(by:), shuffle(), reverse() Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Offers a comprehensive set of in-place and value-returning operations for reordering elements, consistent with the `MutableCollection` API. `sort()` and `sorted()` without arguments are available when the element type conforms to `Comparable`. ```APIDOC ## `sort(by:)` / `sorted(by:)` / `shuffle()` / `reverse()` — Reordering Full suite of in-place and value-returning reordering operations, matching the `MutableCollection` API. `sort()` / `sorted()` (without arguments) are available when `Element` conforms to `Comparable`. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [ User(id: "u_3", name: "Carol", score: 95), User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] // Sort in-place by score descending users.sort(by: { $0.score > $1.score }) print(users.map(\.name)) // ["Alice", "Carol", "Bob"] // Value-returning sorted copy let byName = users.sorted(by: { $0.name < $1.name }) print(byName.map(\.name)) // ["Alice", "Bob", "Carol"] print(users.map(\.name)) // ["Alice", "Carol", "Bob"] — original unchanged // Reverse in place users.reverse() print(users.map(\.name)) // ["Bob", "Carol", "Alice"] // Shuffle users.shuffle() ``` ``` -------------------------------- ### remove(atOffsets:) and removeAll(where:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Provides methods for efficient bulk removal of elements from an IdentifiedArray. `remove(atOffsets:)` is designed for direct integration with SwiftUI's `IndexSet` from `onDelete`, while `removeAll(where:)` removes elements based on a predicate. ```APIDOC ## `remove(atOffsets:)` and `removeAll(where:)` — Bulk Removal SwiftUI's `onDelete` modifier provides an `IndexSet`; `remove(atOffsets:)` handles this directly. `removeAll(where:)` removes all elements satisfying a predicate while preserving relative order. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Task A", isComplete: true), Todo(id: UUID(), title: "Task B", isComplete: false), Todo(id: UUID(), title: "Task C", isComplete: true), ] // SwiftUI List onDelete integration todos.remove(atOffsets: IndexSet([0, 2])) print(todos.map(\.title)) // ["Task B"] // Remove all completed todos = [ Todo(id: UUID(), title: "Task A", isComplete: true), Todo(id: UUID(), title: "Task B", isComplete: false), Todo(id: UUID(), title: "Task C", isComplete: true), ] todos.removeAll(where: \.isComplete) print(todos.map(\.title)) // ["Task B"] ``` ``` -------------------------------- ### Add Identified Collections as a SwiftPM Dependency Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/Sources/IdentifiedCollections/Documentation.docc/IdentifiedCollections.md Include Identified Collections in your SwiftPM project by adding the package URL to your dependencies. ```swift dependencies: [ .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "0.5.0") ], ``` -------------------------------- ### ViewModel Function to Toggle Todo Completion by Index Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md An alternative method in `TodosViewModel` that toggles a todo's completion status using its index. This approach can be simpler but has stability issues. ```swift class TodosViewModel: ObservableObject { ... func todoCheckboxToggled(at index: Int) { self.todos[index].isComplete.toggle() // TODO: Update todo on backend using an API client } } ``` -------------------------------- ### O(1) ID-Based Access and Mutation with subscript(id:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Access and mutate elements in O(1) time using their ID. Assigning nil removes the element; assigning a value upserts it. ```swift import IdentifiedCollections struct User: Identifiable { let id: String var name: String var score: Int } var users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] // Read let alice = users[id: "u_1"] // Optional(User(id: "u_1", name: "Alice", score: 100)) // Mutate in-place (safe even after async work — no index drift) users[id: "u_1"]?.score += 50 print(users[id: "u_1"]?.score) // Optional(150) // Upsert: appends if not present users[id: "u_3"] = User(id: "u_3", name: "Carol", score: 95) print(users.count) // 3 // Remove by assigning nil users[id: "u_2"] = nil print(users.map(\.name)) // ["Alice", "Carol"] ``` -------------------------------- ### Construct IdentifiedArray with ID Key Path Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Create an IdentifiedArray using a key path to specify the identifier for elements, similar to how SwiftUI's List and ForEach work. This does not require the element type to conform to Identifiable. ```swift var numbers = IdentifiedArray(id: \Int.self) ``` -------------------------------- ### move(fromOffsets:toOffset:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Facilitates reordering of elements within an IdentifiedArray, directly integrating with SwiftUI's `onMove` modifier. It accepts source offsets and a destination offset, maintaining the relative order of the moved elements. ```APIDOC ## `move(fromOffsets:toOffset:)` — Reordering for SwiftUI Directly integrates with SwiftUI's `onMove` modifier by accepting `IndexSet` source offsets and a destination integer offset, preserving relative order of moved elements. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "First", isComplete: false), Todo(id: UUID(), title: "Second", isComplete: false), Todo(id: UUID(), title: "Third", isComplete: false), ] // Move "First" and "Second" after "Third" todos.move(fromOffsets: IndexSet([0, 1]), toOffset: 3) print(todos.map(\.title)) // ["Third", "First", "Second"] // SwiftUI List onMove integration struct TodoListView: View { @Binding var todos: IdentifiedArrayOf var body: some View { List { ForEach(todos) { todo in Text(todo.title) } .onMove { source, destination in todos.move(fromOffsets: source, toOffset: destination) } } } } ``` ``` -------------------------------- ### Reorder Elements with `move(fromOffsets:toOffset:)` Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Integrates with SwiftUI's `onMove` modifier to reorder elements using `IndexSet` and a destination offset, maintaining relative order. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "First", isComplete: false), Todo(id: UUID(), title: "Second", isComplete: false), Todo(id: UUID(), title: "Third", isComplete: false), ] // Move "First" and "Second" after "Third" todos.move(fromOffsets: IndexSet([0, 1]), toOffset: 3) print(todos.map(\.title)) // ["Third", "First", "Second"] // SwiftUI List onMove integration struct TodoListView: View { @Binding var todos: IdentifiedArrayOf var body: some View { List { ForEach(todos) { todo in Text(todo.title) } .onMove { source, destination in todos.move(fromOffsets: source, toOffset: destination) } } } } ``` -------------------------------- ### Index Lookup by ID with `index(id:)` Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Returns the integer index of an element by its ID in O(1) time, or `nil` if not found. Useful for slicing operations. ```swift import IdentifiedCollections let users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), User(id: "u_3", name: "Carol", score: 95), ] print(users.index(id: "u_2")) // Optional(1) print(users.index(id: "u_99")) // nil // Use with slicing if let idx = users.index(id: "u_2") { let tail = users[idx...] print(tail.map(\.name)) // ["Bob", "Carol"] } ``` -------------------------------- ### ViewModel Function with Asynchronous Update by Index (Unsafe) Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Illustrates a potential pitfall when updating a todo item asynchronously using its index. The index might become invalid after the async operation, leading to incorrect updates or crashes. ```swift class TodosViewModel: ObservableObject { ... func todoCheckboxToggled(at index: Int) async { self.todos[index].isComplete.toggle() do { // ❌ Could update the wrong todo, or crash! self.todos[index] = try await self.apiClient.updateTodo(self.todos[index]) } catch { // Handle error } } } ``` -------------------------------- ### TodosViewModel with Published Array Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md A sample `TodosViewModel` using `@Published` to manage an array of `Todo` objects, suitable for SwiftUI views. ```swift class TodosViewModel: ObservableObject { @Published var todos: [Todo] = [] } ``` -------------------------------- ### Async-Safe Mutation with IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Demonstrates how IdentifiedArray's id-based subscripting ensures safe mutation after async suspension points, avoiding index invalidation issues. ```swift import IdentifiedCollections class TodosViewModel: ObservableObject { @Published var todos: IdentifiedArrayOf = [] func todoCheckboxToggled(id: Todo.ID) async { // Optimistic local update todos[id: id]?.isComplete.toggle() do { // After await, index-based access would be unsafe — id-based is not let updated = try await apiClient.updateTodo(todos[id: id]!) todos[id: id] = updated // ✅ Always updates the correct element } catch { todos[id: id]?.isComplete.toggle() // Revert on failure } } } ``` -------------------------------- ### Reorder Elements: `sort`, `sorted`, `shuffle`, `reverse` Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Provides in-place and value-returning reordering operations matching `MutableCollection` API. `sort()`/`sorted()` are available when `Element` conforms to `Comparable`. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [ User(id: "u_3", name: "Carol", score: 95), User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] // Sort in-place by score descending users.sort(by: { $0.score > $1.score }) print(users.map(\.name)) // ["Alice", "Carol", "Bob"] // Value-returning sorted copy let byName = users.sorted(by: { $0.name < $1.name }) print(byName.map(\.name)) // ["Alice", "Bob", "Carol"] print(users.map(\.name)) // ["Alice", "Carol", "Bob"] — original unchanged // Reverse in place users.reverse() print(users.map(\.name)) // ["Bob", "Carol", "Alice"] // Shuffle users.shuffle() ``` -------------------------------- ### index(id:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Provides an efficient O(1) lookup for the integer index of an element using its ID. Returns `nil` if the ID is not found, and is useful for subsequent index-based slicing operations. ```APIDOC ## `index(id:)` — Index Lookup by ID Returns the integer index of the element with the given id in expected O(1) time, or `nil` if not present. Useful when you need the position for index-based slicing operations. ```swift import IdentifiedCollections let users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), User(id: "u_3", name: "Carol", score: 95), ] print(users.index(id: "u_2")) // Optional(1) print(users.index(id: "u_99")) // nil // Use with slicing if let idx = users.index(id: "u_2") { let tail = users[idx...] print(tail.map(\.name)) // ["Bob", "Carol"] } ``` ``` -------------------------------- ### IdentifiedArray subscript(id:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Explains the O(1) ID-based subscript for reading, mutating, upserting, and removing elements from an IdentifiedArray. ```APIDOC ## subscript(id:) — O(1) ID-Based Access and Mutation The id-based subscript is the central API of `IdentifiedArray`. It provides expected O(1) read and write access by identifier, eliminating the need for linear `firstIndex(where:)` traversals. Assigning `nil` removes the element; assigning a value upserts it (append if new, overwrite in-place if existing). ```swift import IdentifiedCollections struct User: Identifiable { let id: String var name: String var score: Int } var users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), ] // Read let alice = users[id: "u_1"] // Optional(User(id: "u_1", name: "Alice", score: 100)) // Mutate in-place (safe even after async work — no index drift) users[id: "u_1"]?.score += 50 print(users[id: "u_1"]?.score) // Optional(150) // Upsert: appends if not present users[id: "u_3"] = User(id: "u_3", name: "Carol", score: 95) print(users.count) // 3 // Remove by assigning nil users[id: "u_2"] = nil print(users.map(\.name)) // ["Alice", "Carol"] ``` ``` -------------------------------- ### Remove Elements by IndexSet or Predicate Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Use `remove(atOffsets:)` for SwiftUI's `IndexSet` integration and `removeAll(where:)` to remove elements matching a condition, preserving relative order. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Task A", isComplete: true), Todo(id: UUID(), title: "Task B", isComplete: false), Todo(id: UUID(), title: "Task C", isComplete: true), ] // SwiftUI List onDelete integration todos.remove(atOffsets: IndexSet([0, 2])) print(todos.map(\.title)) // ["Task B"] // Remove all completed todos = [ Todo(id: UUID(), title: "Task A", isComplete: true), Todo(id: UUID(), title: "Task B", isComplete: false), Todo(id: UUID(), title: "Task C", isComplete: true), ] todos.removeAll(where: \.isComplete) print(todos.map(\.title)) // ["Task B"] ``` -------------------------------- ### ViewModel Function to Toggle Todo Completion by ID Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md A method within `TodosViewModel` to toggle the `isComplete` status of a todo item identified by its `id`. This involves finding the index first. ```swift class TodosViewModel: ObservableObject { ... func todoCheckboxToggled(at id: Todo.ID) { guard let index = self.todos.firstIndex(where: { $0.id == id }) else { return } self.todos[index].isComplete.toggle() // TODO: Update todo on backend using an API client } } ``` -------------------------------- ### Workaround for Enumerated List in SwiftUI Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/Sources/IdentifiedCollections/Documentation.docc/IdentifiedCollections.md When needing to pass enumerated data to SwiftUI's `List` or `ForEach` before native support, construct an array from the enumerated collection. This is a workaround for compatibility. ```swift List(Array(self.viewModel.todos.enumerated()), id: \.element.id) { index, todo in ... } ``` -------------------------------- ### Define Identifiable Todo Struct Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Defines a basic `Todo` struct conforming to `Identifiable` protocol, essential for use in SwiftUI lists and collections. ```swift struct Todo: Identifiable { var description = "" let id: UUID var isComplete = false } ``` -------------------------------- ### IdentifiedArray with Custom Key Path Identity Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Use a key path to a Hashable property as the identifier for elements not conforming to Identifiable. Supports self-identity for value types. ```swift import IdentifiedCollections struct Product { var sku: String var name: String var price: Double } // Use `\.sku` as the identity key path var inventory = IdentifiedArray(id: \Product.sku) inventory.append(Product(sku: "ABC-001", name: "Widget", price: 9.99)) inventory.append(Product(sku: "ABC-002", name: "Gadget", price: 19.99)) // Self-identity for value types like Int or String var numbers = IdentifiedArray(id: \Int.self) numbers.append(contentsOf: [1, 2, 3, 4, 5]) print(numbers[id: 3]) // Optional(3) ``` -------------------------------- ### Filter Elements with `filter(_:)` Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Returns a new `IdentifiedArray` containing elements that satisfy a predicate, preserving the id key path and element order. The return type is `IdentifiedArray`, not a plain `Array`. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Buy milk", isComplete: true), Todo(id: UUID(), title: "Walk dog", isComplete: false), Todo(id: UUID(), title: "Read book", isComplete: true), Todo(id: UUID(), title: "Write tests", isComplete: false), ] let pending: IdentifiedArrayOf = todos.filter { !$0.isComplete } print(pending.map(\.title)) // ["Walk dog", "Write tests"] print(type(of: pending)) // IdentifiedArray ``` -------------------------------- ### Unconditional Upsert Operations in IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Provides methods to either update an existing element by ID or append it if new. `updateOrInsert(_:at:)` also allows specifying an insertion index. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), ] // Replace existing let old = users.updateOrAppend(User(id: "u_1", name: "Alice", score: 200)) print(old?.score) // Optional(100) print(users[id: "u_1"]?.score) // Optional(200) // Append new let none = users.updateOrAppend(User(id: "u_2", name: "Bob", score: 80)) print(none) // nil print(users.count) // 2 // Insert at specific position let (original, idx) = users.updateOrInsert(User(id: "u_0", name: "Zara", score: 99), at: 0) print(original, idx) // nil, 0 print(users.map(\.name)) // ["Zara", "Alice", "Bob"] ``` -------------------------------- ### Declare IdentifiedArrayOf Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Initialize IdentifiedArrayOf from literals or sequences. This type alias is for elements conforming to Identifiable. ```swift import IdentifiedCollections struct Todo: Identifiable, Equatable { let id: UUID var title: String var isComplete: Bool } // Literal initialization — identical to [Todo] syntax var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Buy groceries", isComplete: false), Todo(id: UUID(), title: "Call Mom", isComplete: false), ] // From an existing sequence let fetched: [Todo] = fetchTodosFromServer() var todosFromServer = IdentifiedArrayOf(uniqueElements: fetched) // Empty initialization var empty: IdentifiedArrayOf = [] print(empty.count) // 0 ``` -------------------------------- ### Codable Support for IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt IdentifiedArray encodes as a flat JSON array, making it compatible with standard `[Element]` representations. Decoding throws `DecodingError.dataCorrupted` if duplicate IDs are encountered. ```swift import IdentifiedCollections struct Player: Identifiable, Codable { let id: Int var name: String var level: Int } let players: IdentifiedArrayOf = [ Player(id: 1, name: "Link", level: 42), Player(id: 2, name: "Zelda", level: 99), ] // Encodes as a plain JSON array — interoperable with any [Player] consumer let json = try JSONEncoder().encode(players) print(String(data: json, encoding: .utf8)!) // [{"id":1,"name":"Link","level":42},{"id":2,"name":"Zelda","level":99}] // Decodes back, enforcing uniqueness let restored = try JSONDecoder().decode(IdentifiedArrayOf.self, from: json) print(restored[id: 1]?.name) // Optional("Link") // Duplicate id throws DecodingError.dataCorrupted let badJSON = Data(#"[{"id":1,"name":"A","level":1},{"id":1,"name":"B","level":2}]"#.utf8) do { _ = try JSONDecoder().decode(IdentifiedArrayOf.self, from: badJSON) } catch DecodingError.dataCorrupted(let ctx) { print(ctx.debugDescription) // "Duplicate element at offset 1" } ``` -------------------------------- ### Insert Element at Specific Index in IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Inserts an element at a specified index. If an element with the same ID exists, the operation is a no-op and returns the existing element's index. Useful for maintaining order. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_3", name: "Carol", score: 95), ] // Insert Bob at position 1 let (inserted, index) = users.insert(User(id: "u_2", name: "Bob", score: 80), at: 1) print(inserted, index) // true, 1 print(users.map(\.name)) // ["Alice", "Bob", "Carol"] // Attempting to insert a duplicate returns the existing index let (dup, dupIdx) = users.insert(User(id: "u_1", name: "Alice Again", score: 0), at: 0) print(dup, dupIdx) // false, 0 ``` -------------------------------- ### Use IdentifiedArray with SwiftUI Lists Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Pass an IdentifiedArray directly to SwiftUI views like List and ForEach. This simplifies data management and iteration over identifiable collections. ```swift List(self.viewModel.todos) { todo in ... } ``` -------------------------------- ### filter(_:) Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Returns a new `IdentifiedArray` containing only elements that satisfy a given predicate. This operation is type-preserving, meaning it returns an `IdentifiedArray` and not a standard `Array`, while maintaining the original id key path and element order. ```APIDOC ## `filter(_:)` — Type-Preserving Filter Returns a new `IdentifiedArray` (not a plain `Array`) containing only elements satisfying the predicate, preserving the id key path and element order. ```swift import IdentifiedCollections var todos: IdentifiedArrayOf = [ Todo(id: UUID(), title: "Buy milk", isComplete: true), Todo(id: UUID(), title: "Walk dog", isComplete: false), Todo(id: UUID(), title: "Read book", isComplete: true), Todo(id: UUID(), title: "Write tests", isComplete: false), ] let pending: IdentifiedArrayOf = todos.filter { !$0.isComplete } print(pending.map(\.title)) // ["Walk dog", "Write tests"] print(type(of: pending)) // IdentifiedArray ``` ``` -------------------------------- ### Remove Elements by ID or Value from IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Demonstrates removing elements using their ID, by providing the element's value (matching on ID), or by integer index. Returns the removed element or nil if not found. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [ User(id: "u_1", name: "Alice", score: 100), User(id: "u_2", name: "Bob", score: 80), User(id: "u_3", name: "Carol", score: 95), ] // Remove by id let removed = users.remove(id: "u_2") print(removed?.name) // Optional("Bob") print(users.map(\.name)) // ["Alice", "Carol"] // Remove by value (matched on id) let alice = User(id: "u_1", name: "Alice", score: 100) users.remove(alice) print(users.map(\.name)) // ["Carol"] // Remove by index users.remove(at: 0) print(users.isEmpty) // true ``` -------------------------------- ### Wrap Values with Explicit IDs using Identified Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt The `Identified` struct wraps any value with an explicit ID, making it `Identifiable` without modifying the original type. It supports `@dynamicMemberLookup` for direct access to wrapped value members. ```swift import IdentifiedCollections // Wrap a plain String with a UUID let identified = Identified("Hello, World!", id: UUID()) print(identified.id) // some UUID print(identified.value) // "Hello, World!" // Use key path initializer let identified2 = Identified(42, id: \.self) print(identified2.id) // 42 // @dynamicMemberLookup forwards to the wrapped value struct Config { var host: String var port: Int } let cfg = Identified(Config(host: "localhost", port: 8080), id: UUID()) print(cfg.host) // "localhost" — forwarded via dynamic member lookup print(cfg.port) // 8080 // Use in an IdentifiedArray var configs: IdentifiedArray> = [] configs.append(cfg) ``` -------------------------------- ### Declare IdentifiedArray in ViewModel Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Use IdentifiedArrayOf to manage collections of identifiable elements within a ViewModel. This allows for direct id-based subscripting for mutations. ```swift import IdentifiedCollections class TodosViewModel: ObservableObject { @Published var todos: IdentifiedArrayOf = [] ... } ``` -------------------------------- ### Append Element to IdentifiedArray Source: https://context7.com/pointfreeco/swift-identified-collections/llms.txt Appends an element if its ID is not already present. Returns a tuple indicating if insertion occurred and the element's index. Duplicate IDs are ignored. ```swift import IdentifiedCollections var users: IdentifiedArrayOf = [] let (inserted1, idx1) = users.append(User(id: "u_1", name: "Alice", score: 100)) print(inserted1, idx1) // true, 0 // Duplicate — not inserted let (inserted2, idx2) = users.append(User(id: "u_1", name: "Alice Duplicate", score: 0)) print(inserted2, idx2) // false, 0 // Bulk append — duplicates skipped automatically let newUsers = [User(id: "u_2", name: "Bob", score: 80), User(id: "u_1", name: "Dup", score: 0)] users.append(contentsOf: newUsers) print(users.map(\.name)) // ["Alice", "Bob"] ``` -------------------------------- ### Mutate Element by ID in IdentifiedArray Source: https://github.com/pointfreeco/swift-identified-collections/blob/main/README.md Mutate an element directly using its ID as a subscript in an IdentifiedArray. This is useful for updating elements after asynchronous operations, ensuring the latest state is reflected. ```swift class TodosViewModel: ObservableObject { ... func todoCheckboxToggled(at id: Todo.ID) async { self.todos[id: id]?.isComplete.toggle() do { // 1️⃣ Update todo on backend and mutate it in the todos identified array. self.todos[id: id] = try await self.apiClient.updateTodo(self.todos[id: id]!) } catch { // Handle error } // No step 2️⃣ 😆 } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.