Skip to content

Instantly share code, notes, and snippets.

import Foundation
final class SafeSyncQueue {
struct QueueIdentity {
let label: String
}
let queue: DispatchQueue
@khanlou
khanlou / Collection+Chunking.swift
Last active December 23, 2020 02:00
Collection chunking via @timvermeulen
extension Collection {
func chunk(size: Int) -> ChunkedCollection<Self> {
ChunkedCollection(self, size: size)
}
}
struct ChunkedCollection<Base: Collection>: Collection {
private let base: Base
//
// GregorianDate.swift
//
//
// Created by Soroush Khanlou on 12/22/20.
//
import Foundation
public struct GregorianDate: Equatable, Hashable, Comparable, Codable, CustomStringConvertible {
extension Sequence {
func eachPair() -> Zip2Sequence<Self, DropFirstSequence<Self>> {
return zip(self, self.dropFirst())
}
}
extension Collection {
func indexed() -> [(index: Index, element: Element)] {
return zip(indices, self).map({ (index: $0, element: $1) })
@khanlou
khanlou / YouDeserveNiceErrors.swift
Last active October 18, 2020 03:00
Nicer descriptions for DecodingErrors
extension DecodingError.Context {
var pathDescription: String {
pathDescription(for: codingPath)
}
func path(including final: CodingKey) -> String {
pathDescription(for: codingPath + [final])
}
private func pathDescription(for path: [CodingKey]) -> String {

Sum With Block

Introduction

While Swift’s Sequence models brings a lot of niceties that we didn’t have access to in Objective-C, like map and filter, there are other useful operations on sequences that the standard library doesn’t support yet. One operation that is currently missing is summing numeric values on elements in a sequence.

extension Sequence {
func sum<T>(_ transform: (Element) -> T) -> T where T: AdditiveArithmetic {
var sum = T.zero
for element in self {
sum += transform(element)
}
return sum
}
}
import UIKit
protocol StoryboardInitializable {
static var storyboardName: String { get }
static var storyboardIdentifier: String { get }
static func makeFromStoryboard() -> Self
}
extension StoryboardInitializable {
public struct Credentials {
public init(key: String, secret: String) {
self.key = key
self.secret = secret
}
public let key: String
public let secret: String
}
struct Statistics {
private(set) var count: Double = 0
private(set) var sum: Double = 0
private(set) var sumOfSquares: Double = 0
var average: Double {
sum / count
}