Skip to content

Instantly share code, notes, and snippets.

View ketzusaka's full-sized avatar

james ketzusaka

  • Tools for Humanity
  • San Francisco, CA
  • 20:29 (UTC -07:00)
View GitHub Profile
@ketzusaka
ketzusaka / SampleWidget.swift
Created June 30, 2023 22:36
widget example
import SwiftUI
import WidgetKit
struct Mode1: Codable {
var foo: String
}
struct Mode2: Codable {
var bar: String
}
// Current HTTPStream:
protocol HTTPStream: Stream {
static func makeStream() -> Self
func bind(to ip: String?, on port: Int) throws
func accept(max connectionCount: Int, handler: (HTTPStream -> Void)) throws
func listen() throws
func receiveByte() throws -> Byte?
@ketzusaka
ketzusaka / gist:fc5019109b486c411a3d
Created February 25, 2016 19:52
Any to Array of Any fail
let items = [1, 2, 3] as Any
if let items = items as? [Any] { // This cast fails
print("it works") // and this is never printed
}
@ketzusaka
ketzusaka / gist:6ce4731c8eef9f2c984d
Created October 23, 2015 17:30
Associated enums with Cereal
enum Job {
case Mechanic(String)
case Carpenter(String)
}
extension Job: CerealType {
private struct Keys {
static let job = "job"
static let name = "name"
}
import CoreData
class WBManagedElement: NSManagedObject {
}
class ElementParameter: NSObject, NSSecureCoding {
private struct Keys {
static let element = "element"
protocol Watable { }
extension Array: Watable { }
func test<Type: Watable>(v: Type) {
// Is there a way to tell if Type is an array with any type?
}
protocol Watable { }
func arrayTest<Type: Watable>(v: [Type]) {
if let unwrapped = v as? [Watable] {
print("Success!: \(unwrapped)")
} else {
print("Failed :(")
}
}
@ketzusaka
ketzusaka / first.swift
Created July 20, 2015 19:20
First in Swift
/**
Find the first element in a sequence passing a test.
:param: source Source sequence to iterate
:param: includeElement Closure to evaluate elements with
:return: First element in the sequence for which includeElement returns true, or nil if none found
*/
public func first<S: SequenceType>(source: S, includeElement: (S.Generator.Element) -> Bool) -> S.Generator.Element? {
var filteredSource = lazy(source).filter(includeElement).generate()
return filteredSource.next()
@ketzusaka
ketzusaka / genscoped-variables.swift
Created July 17, 2015 16:44
Generator-scoped variables
func anyGenerator<Element>(initial: Element, body: (inout Element) -> Element?) -> AnyGenerator<Element> {
return {
var i: Element? = initial
return anyGenerator {
var r: Element?
if var x = i {
r = body(&x)
i = x
}
@ketzusaka
ketzusaka / gist:acedad5c25e6db1acadd
Created July 16, 2015 17:39
Fancy ObserverContext
import Foundation
public class ObserverContext: NSObject {
public let keyPath: String
public let options: NSKeyValueObservingOptions
public var context = 0
public init(keyPath: String, options: NSKeyValueObservingOptions = nil) {
self.keyPath = keyPath
self.options = options
}