TM-SGNL-iOS/SignalServiceKit/Util/Collection+OWS.swift
TeleMessage developers dde0620daf initial commit
2025-05-03 12:28:28 -07:00

35 lines
962 B
Swift

//
// Copyright 2018 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
public extension Collection {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
@inlinable
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
public extension BidirectionalCollection {
@inlinable
func suffix(while predicate: (Element) throws -> Bool) rethrows -> Self.SubSequence {
guard let startIndex = try self.lastIndex(where: { try !predicate($0) }) else {
return self[...]
}
return self[startIndex...].dropFirst()
}
}
public extension RandomAccessCollection {
func chunked(by chunkSize: Int) -> [SubSequence] {
stride(from: 0, to: count, by: chunkSize).map {
dropFirst($0).prefix(chunkSize)
}
}
@inlinable var nilIfEmpty: Self? {
isEmpty ? nil : self
}
}