Skip to content

Instantly share code, notes, and snippets.

@54lihaoxin
54lihaoxin / Heap.swift
Created February 9, 2019 06:39
A simple binary heap
import Foundation
/// A simple binary heap
final class Heap<T: Comparable> {
private let isMinHeap: Bool
private let comparator: (T, T) -> Bool
private var heap: [T] = []
var isEmpty: Bool { return heap.isEmpty }
var count: Int { return heap.count }
extension KeyedDecodingContainer {
/// The sole purpose of this `EmptyDecodable` is allowing decoder to skip an element that cannot be decoded.
private struct EmptyDecodable: Decodable {}
/// Return successfully decoded elements even if some of the element fails to decode.
func safelyDecodeArray<T: Decodable>(of type: T.Type, forKey key: KeyedDecodingContainer.Key) -> [T] {
guard var container = try? nestedUnkeyedContainer(forKey: key) else {
return []
}