Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
Add support for ID subscripts
Browse files Browse the repository at this point in the history
  • Loading branch information
david-swift committed Apr 4, 2024
1 parent 50b2211 commit 1dbde17
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 16 deletions.
35 changes: 35 additions & 0 deletions Sources/Adwaita/Model/Data Flow/Binding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,38 @@ public struct Binding<Value> {
}

}

extension Binding where Value: MutableCollection {

/// Get a child at a certain index of the array as a binding.
/// - Parameters:
/// - index: The child's index.
/// - defaultValue: The value used if the index is out of range does not exist.
/// - Returns: The child as a binding.
public subscript(safe index: Value.Index?, default defaultValue: Value.Element) -> Binding<Value.Element> {
.init {
if let index, wrappedValue.indices.contains(index) {
return wrappedValue[index] ?? defaultValue
}
return defaultValue
} set: { newValue in
if let index, wrappedValue.indices.contains(index) {
wrappedValue[index] = newValue
}
}
}

}

extension Binding where Value: MutableCollection, Value.Element: Identifiable {

/// Get a child of the array with a certain id as a binding.
/// - Parameters:
/// - id: The child's id.
/// - defaultValue: The value used if the index is out of range does not exist.
/// - Returns: The child as a binding.
public subscript(id: Value.Element.ID?, default defaultValue: Value.Element) -> Binding<Value.Element> {
self[safe: wrappedValue.firstIndex { $0.id == id }, default: defaultValue]
}

}
27 changes: 11 additions & 16 deletions Sources/Adwaita/Model/Extensions/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,24 +105,19 @@ extension Array {

}

extension Binding where Value: MutableCollection {
extension Array where Element: Identifiable {

/// Get a child at a certain index of the array as a binding.
/// Accesses the element with a certain id safely.
/// - Parameters:
/// - index: The child's index.
/// - defaultValue: The value used if the index is out of range does not exist.
/// - Returns: The child as a binding.
public subscript(safe index: Value.Index?, default defaultValue: Value.Element) -> Binding<Value.Element> {
.init {
if let index, wrappedValue.indices.contains(index) {
return wrappedValue[index] ?? defaultValue
}
return defaultValue
} set: { newValue in
if let index, wrappedValue.indices.contains(index) {
wrappedValue[index] = newValue
}
}
/// - id: The child's id.
///
/// Access and set elements the safe way:
/// ```swift
/// var array = ["Hello", "World"]
/// print(array[safe: 2] ?? "Out of range")
/// ```
public subscript(id: Element.ID) -> Element? {
self[safe: firstIndex { $0.id == id }]
}

}

0 comments on commit 1dbde17

Please sign in to comment.