Skip to content

Instantly share code, notes, and snippets.

import AsyncHTTPClient
import Foundation
struct ServerSentEvent {
let name: String
let data: String
init(_ substring: Substring) {
let lines = substring.split(whereSeparator: \.isNewline)
self.name = String(lines
//
// ContentView.swift
// DependentEnvironment
//
// Created by Soroush Khanlou on 3/27/23.
//
import SwiftUI
struct Inner: View {
struct BundleVersion: Comparable {
let tuple: (Int, Int, Int)
init(string: String) {
let numbers = string.split(separator: ".").compactMap({ Int($0) })
let major = numbers.count >= 1 ? numbers[0] : 0
let minor = numbers.count >= 2 ? numbers[1] : 0
let patch = numbers.count >= 3 ? numbers[2] : 0
import SwiftUI
struct IdentifiableError: Identifiable {
let error: Error
var id: String {
let nsError = error as NSError
return "\(nsError.domain) \(nsError.code)"
}
@khanlou
khanlou / CanCan.swift
Created February 14, 2021 03:09
A version of Ruby's cancan for Swift.
import Foundation
struct CanCan<Identity, Action: Equatable> {
var registry: [(String, (Identity, Any) -> [Action])] = []
mutating func register<T>(_ type: T.Type, _ block: @escaping (Identity, T) -> [Action]) {
self.registry.append((String(describing: type), { (identity: Identity, object: Any) -> [Action] in
guard let casted = object as? T else {
return []

This is a quick way to approximate how many person-hours have put into a git repo.

git log --pretty=format:"%ae %ad" --date=format:'%Y-%m-%d %H' | uniq | wc -l

The --pretty=format gives you the author email and commit date, and the date is formatted to just include the year, month, day and hour, like so: 2020-12-22 16. You can add a grep before or after the unique to filter out by author. wc -l tells you the number of lines, which are uniqued, meaning if you had two commits in the same hour, those are filtered out.

//
// IndexedForEach.swift
//
//
// Created by Soroush Khanlou on 1/21/20.
//
//
import Foundation
import SwiftUI
//
// GregorianDate.swift
//
//
// Created by Soroush Khanlou on 12/22/20.
//
import Foundation
public struct GregorianDate: Equatable, Hashable, Comparable, Codable, CustomStringConvertible {

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
}
}