From adbd1c2a0082ff7181b6666e23446f165730c2da Mon Sep 17 00:00:00 2001 From: david-swift Date: Thu, 4 Apr 2024 15:29:31 +0200 Subject: [PATCH] Add shortcut for getting element of array binding --- Sources/Adwaita/Model/Extensions/Array.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Sources/Adwaita/Model/Extensions/Array.swift b/Sources/Adwaita/Model/Extensions/Array.swift index e8566d0..2609c75 100644 --- a/Sources/Adwaita/Model/Extensions/Array.swift +++ b/Sources/Adwaita/Model/Extensions/Array.swift @@ -104,3 +104,20 @@ extension Array { } } + +extension Binding where Value == [Any] { + + /// 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: Int?, default defaultValue: Value.Element) -> Binding { + .init { + wrappedValue[safe: index] ?? defaultValue + } set: { newValue in + wrappedValue[safe: index] = newValue + } + } + +}