Skip to content

Instantly share code, notes, and snippets.


Sum With Block


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.

View SumWithBlock.swift
extension Sequence {
func sum<T>(_ transform: (Element) -> T) -> T where T: AdditiveArithmetic {
var sum =
for element in self {
sum += transform(element)
return sum
khanlou / YouDeserveNiceErrors.swift
Last active Oct 18, 2020
Nicer descriptions for DecodingErrors
View YouDeserveNiceErrors.swift
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 {

This is designed to look like sheet(item:content:):

func sheet<Item, Content>(item: Binding<Item?>, content: @escaping (Item) -> Content) -> some View

But for pushing views instead of presenting them as sheets.

To use it, create a @State variable for your selected item:

@State var selectedPerson: Person?
View Geohelpers.swift
import Foundation
import MapKit
extension MKMapPoint {
static var nyc: MKMapPoint {
return MKMapPoint(.nyc)
extension MKMapRect {
View Statistics.swift
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
khanlou / Rope.swift
Last active Jul 6, 2020
A little...ropes course
View Rope.swift
struct Rope {
enum Node: ExpressibleByStringLiteral {
case leaf(String, length: Int)
indirect case branch(left: Node, right: Node?, length: Int)
public init(stringLiteral value: StaticString) {
let string = "\(value)"
self = .leaf(string, length: string.count)
View ScalableFonts.swift
import SwiftUI
enum ScalableFont {
case system(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default)
case custom(_ name: String, size: CGFloat)
var size: CGFloat {
switch self {
View ActivityIndicator.swift
// Spinner.swift
// spinner
// Created by Soroush Khanlou on 5/29/20.
// Copyright © 2020 Soroush Khanlou. All rights reserved.
import SwiftUI
khanlou / A - Usage.swift
Last active Jun 4, 2020
This ScrollView has a modifier called `onScroll`, which is updated when scrolls occur.
View A - Usage.swift
struct ContentView: View {
@State var scrollOffset: CGPoint = .zero
var body: some View {
ObservableScrollView {
Text("Hello, world!")
.foregroundColor(self.scrollOffset.y == 0 ? .blue : .red)
.onScroll { self.scrollOffset = $0 }
You can’t perform that action at this time.