Files
purchases-ios/Sources/FoundationExtensions/Array+Extensions.swift
T

52 lines
1.2 KiB
Swift
Raw Normal View History

2022-02-23 18:05:59 -05:00
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Array+Extensions.swift
//
// Created by Nacho Soto on 2/17/22.
import Foundation
extension Array {
/// Equivalent to `removeFirst()` but it returns `Optional` if the collection is empty.
mutating func popFirst() -> Element? {
guard !self.isEmpty else { return nil }
return self.removeFirst()
}
}
2022-08-22 16:00:39 -07:00
extension Collection {
2023-03-03 16:06:04 -04:00
/// - Returns: an element if and only if it's the only one in the collection
2022-08-22 16:00:39 -07:00
var onlyElement: Element? {
guard self.count == 1, let first = self.first else {
return nil
}
return first
}
/// Returns the element at the specified index if it exists, otherwise nil.
subscript(safe index: Index) -> Element? {
return self.indices.contains(index) ? self[index] : nil
}
2022-08-22 16:00:39 -07:00
}
extension Sequence where Element: AdditiveArithmetic {
/// - Returns: the sum of the elements in the sequence.
func sum() -> Element {
return reduce(.zero, +)
}
}