Skip to content

Commit

Permalink
Add extensions for Collection, Array, and Set
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdifran committed Sep 1, 2023
1 parent a94138b commit 5c417a5
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Sources/AppFoundations/Extensions/Array/Array+SafeAccess.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// Array+SafeAccess.swift
//
//
// Created by Mark DiFranco on 2023-09-01.
//

import Foundation

public extension Array {

/// Returns the element at `index`, or nil if `index` is out of the bounds.
/// - parameter index: The index of the element to access.
/// - returns: The element at the given index, or `nil` if the index is out of bounds.
func safeAccess(at index: UInt) -> Element? {
guard count > index else { return nil }

return self[Int(index)]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// Collection+Checks.swift
//
//
// Created by Mark DiFranco on 2023-09-01.
//

import Foundation

public extension Collection {

/// Whether `self` is empty or not.
/// - returns: `true` if `self` is not empty, `false` otherwise.
var isNotEmpty: Bool { !isEmpty }
}
16 changes: 16 additions & 0 deletions Sources/AppFoundations/Extensions/Collection/Collection+Set.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// Collection+Set.swift
//
//
// Created by Mark DiFranco on 2023-09-01.
//

import Foundation

public extension Collection where Element: Hashable {

/// Creates a ``Set`` from the elements in `self`.
func asSet() -> Set<Element> {
Set(self)
}
}
30 changes: 30 additions & 0 deletions Sources/AppFoundations/Extensions/Set/Set+Membership.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//
// Set+Membership.swift
//
//
// Created by Mark DiFranco on 2023-09-01.
//

import Foundation

public extension Set {

/// Returns this ``Set`` with `element` inserted.
/// - parameter element: The `Element` to insert.
/// - returns: This ``Set`` with `element` inserted.
func inserting(_ element: Element) -> Self {
var mutatedSelf = self
mutatedSelf.insert(element)
return mutatedSelf
}

/// If the `element` is present in this ``Set``, it is removed. Otherwise, the `element` is inserted.
/// - parameter element: The `Element` to insert.
mutating func toggleMembership(_ element: Element) {
if contains(element) {
remove(element)
} else {
insert(element)
}
}
}

0 comments on commit 5c417a5

Please sign in to comment.