Skip to content

Commit

Permalink
⭐️ Impl: Add Collection+Helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
dominicstop committed Apr 10, 2023
1 parent c455ed8 commit 849351c
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions ios/src_library/Extensions/Collection+Helpers.swift
Original file line number Diff line number Diff line change
@@ -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;
}
};
};

0 comments on commit 849351c

Please sign in to comment.