From 849351c8f25597d00c311f0333ec93c4f18d7e91 Mon Sep 17 00:00:00 2001 From: Dominic Go <18517029+dominicstop@users.noreply.github.com> Date: Mon, 10 Apr 2023 23:19:04 +0800 Subject: [PATCH] =?UTF-8?q?=E2=AD=90=EF=B8=8F=20Impl:=20Add=20`Collection+?= =?UTF-8?q?Helpers`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Extensions/Collection+Helpers.swift | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 ios/src_library/Extensions/Collection+Helpers.swift diff --git a/ios/src_library/Extensions/Collection+Helpers.swift b/ios/src_library/Extensions/Collection+Helpers.swift new file mode 100644 index 00000000..7502d844 --- /dev/null +++ b/ios/src_library/Extensions/Collection+Helpers.swift @@ -0,0 +1,41 @@ +// +// Collection+Helpers.swift +// react-native-ios-modal +// +// Created by Dominic Go on 4/10/23. +// + +import Foundation + +extension Collection { + + public var secondToLast: Element? { + self[safeIndex: self.index(self.indices.endIndex, offsetBy: -2)]; + }; + + public func isOutOfBounds(forIndex index: Index) -> Bool { + return index < self.indices.startIndex || index > self.indices.endIndex; + }; + + /// Returns the element at the specified index if it is within bounds, + /// otherwise nil. + public subscript(safeIndex index: Index) -> Element? { + return self.isOutOfBounds(forIndex: index) ? nil : self[index]; + }; +}; + +extension MutableCollection { + subscript(safeIndex index: Index) -> Element? { + get { + return self.isOutOfBounds(forIndex: index) ? nil : self[index]; + } + + set { + guard let newValue = newValue, + !self.isOutOfBounds(forIndex: index) + else { return }; + + self[index] = newValue; + } + }; +};