Skip to content

Instantly share code, notes, and snippets.

@satishVekariya
Created February 7, 2026 15:26
Show Gist options
  • Select an option

  • Save satishVekariya/faefd88cc04562359188beb7bf5ace58 to your computer and use it in GitHub Desktop.

Select an option

Save satishVekariya/faefd88cc04562359188beb7bf5ace58 to your computer and use it in GitHub Desktop.
public enum ComponentState<T: Sendable>: Sendable {
case `default`
case loading(T)
case loaded(T)
case error(T)
public var isLoading: Bool {
switch self {
case .loading: true
default: false
}
}
public var isLoaded: Bool {
switch self {
case .loaded: true
default: false
}
}
}
extension ComponentState where T: RangeReplaceableCollection {
public var components: T {
switch self {
case .default: T()
case .loading(let components): components
case .loaded(let components): components
case .error(let components): components
}
}
public var count: Int {
components.count
}
public var isEmpty: Bool {
components.isEmpty
}
public mutating func append(contentsOf newComponents: T) {
switch self {
case .default:
break
case .loading:
var current = self.components
current.append(contentsOf: newComponents)
self = .loading(current)
case .loaded:
var current = self.components
current.append(contentsOf: newComponents)
self = .loaded(current)
case .error:
var current = self.components
current.append(contentsOf: newComponents)
self = .error(current)
}
}
/// Removes components at the specified range of indices (more efficient than filtering)
public mutating func remove(at range: Range<Int>) where T.Index == Int {
switch self {
case .default:
break
case .loading:
var current = self.components
current.removeSubrange(range)
self = .loading(current)
case .loaded:
var current = self.components
current.removeSubrange(range)
self = .loaded(current)
case .error:
var current = self.components
current.removeSubrange(range)
self = .error(current)
}
}
/// Removes the last N components (efficient for removing appended loading components)
public mutating func removeLast(_ count: Int) where T.Index == Int {
guard count > 0, self.count >= count else { return }
let startIndex = self.count - count
remove(at: startIndex..<self.count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment