Skip to content

Instantly share code, notes, and snippets.

View fetch.swift
func fetch<Result: Codable>(_ endpoint: Endpoint<Result>, cacheBehavior: CacheBehavior = .cacheElseNetwork) async throws -> Result {
switch cacheBehavior {
case .cacheElseNetwork:
if let cached = self.cache[endpoint.cacheKey] {
return cached.payload
} else {
return try await self.networkFetch(endpoint)
}
case .networkOnly:
return try await self.networkFetch(endpoint)
@davbeck
davbeck / GQL.swift
Created May 2, 2015
GraphQL data structure implemented in Swift
View GQL.swift
import Foundation
protocol GQLNodeArgument {}
extension String: GQLNodeArgument {}
extension NSNumber: GQLNodeArgument {}
class GQLNode: StringLiteralConvertible, ArrayLiteralConvertible, Printable, DebugPrintable {
let name: String?
@davbeck
davbeck / WKUIDelegate.m
Last active Mar 15, 2022
Boilerplate implementation of WKUIDelegate to support Javascript alerts.
View WKUIDelegate.m
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
completionHandler();
@davbeck
davbeck / assets.rb
Last active Jan 5, 2022
Automatic Enum-based Xcassets in Swift
View assets.rb
#!/usr/bin/env ruby
require "active_support"
def assetCatalogsAtPath(path)
results = []
contents = Dir.entries(path)
@davbeck
davbeck / README.md
Created Jun 19, 2019
A wrapper for UICollectionViewDiffableDataSource that also handles updates to data
View README.md

UICollectionViewDiffableDataSource does an excellent job of handling changes to data and updating the items accordingly. However, there seems to be no good way to handle updates to existing items. If you follow the samples that Apple provides and define Equatable and Hashable to use an id instead of the complete models value, value changes won't cause the collection view to update those cells. If you leave Equatable as it should be and have it compare all values of a model, the cell will update, but it will completely replace the old cell, causing an undesirable "flash".

UICollectionViewComparableDataSource wraps a UICollectionViewDiffableDataSource and will check for items that have been updated, but not removed or added.

This allows us to make updates to a cell without completely reloading it. This is especially usefull if your cells have some sort of temporary state.

This is just an expirement. Use at your own risk.

@davbeck
davbeck / DisplayLink.swift
Created Jul 20, 2019
A Combine Publisher version of CADisplayLink.
View DisplayLink.swift
View Binding+NilCoalescing.swift
import SwiftUI
func ?? <T>(optional: Binding<T?>, defaultValue: @escaping @autoclosure () -> T) -> Binding<T> {
return Binding {
optional.wrappedValue ?? defaultValue()
} set: { newValue in
optional.wrappedValue = newValue
}
}
View TextScaling.swift
struct ContentView: View {
var text: Text {
Text("Bacon ipsum dolor amet fatback rump beef ribs jerky pork loin strip steak.")
.font(.headline) +
Text("\nCorned beef t-bone leberkas ball tip tongue burgdoggen picanha swine porchetta flank hamburger strip steak tail pork. Filet mignon prosciutto venison tongue meatball shankle pancetta. Hamburger prosciutto turkey chicken venison tenderloin porchetta spare ribs burgdoggen cupim pork turducken. Short ribs andouille kielbasa short loin beef. Ham kevin pork loin bacon, pastrami turducken jowl pig venison pork shank beef picanha.")
.font(.body)
}
var body: some View {
text
@davbeck
davbeck / Example.swift
Created Jul 31, 2020
Callback api for SwiftUI based on React's useEffect hook
View Example.swift
struct Child: View {
var count: Int
var body: some View {
Text("Child: \(count)")
.useEffect(Int(floor(Double(count) / 2))) { source in
// this only gets called when the source changes
print("onAppear \(source)")
}
}
View ObservablePublisher.swift
import Combine
import Foundation
import SwiftUI
class ObservablePublisher<Output>: ObservableObject {
@Published var output: Output?
@Published var error: Swift.Error?
private var observer: AnyCancellable?
init() {}