Skip to content

Instantly share code, notes, and snippets.

View kengruven's full-sized avatar

Ken Harris kengruven

  • Seattle, WA
View GitHub Profile
@kengruven
kengruven / tree.swift
Created November 5, 2020 19:26
Swift tree structure
// GOALS:
// 1. Two protocols, BasicNode and SpecialNode.
// 2. They both have "var children: Array<...>", so there's an easy way to walk the tree.
// 3. You can build a tree out of parent->child links from:
// - BasicNode -> BasicNode
// - BasicNode -> SpecialNode
// - SpecialNode -> SpecialNode
// (but never SpecialNode -> BasicNode).
// Is it possible to define this structure in Swift?
@kengruven
kengruven / funnyerror.swift
Created May 31, 2020 14:49
nonsense swift program
struct S {
init() { }
}
let s = S()
protocol P {
func f<T>() -> [T]
}
@kengruven
kengruven / ambiguous.swift
Last active April 25, 2018 23:01
Dispatch ambiguity?
func inc(_ x: Int) -> Int {
return x + 1
}
func inc(_ x: Int, by y: Int = 3) -> Int {
return x + y
}
// how does it decide which one to call?
// in this case, it picks the shorter / exact type match:
inc(3)
enum Real {
case notANumber
case positiveInfinity
case negativeInfinity
case floatingPoint
}
func ~=(pattern: Real, value: Double) -> Bool {
switch pattern {
case .notANumber: return value.isNaN
@kengruven
kengruven / crash.swift
Created January 31, 2018 17:20
Swift crash 2018-1-31
// run "xcrun swift", and paste these 3 statements:
enum B {
case x(String)
}
struct A {
let b: B
}
let a = A(b: .x("a")) // (not ""!)
// then, paste this line:
@kengruven
kengruven / String+Regex.swift
Last active November 5, 2020 18:57
Make NSRegex less painful
import Foundation
// inspired by <http://nshipster.com/nsregularexpression/>
extension String {
var nsrange: NSRange {
NSRange(location: 0, length: utf16.count)
}
func substring(with range: NSRange) -> String {
(self as NSString).substring(with: range)
import math
# "In a study of nearly half a million volunteers in China, those who
# ate chilies just a couple times a week had a 10 percent lower risk
# of death."
# http://www.scientificamerican.com/podcast/episode/spicy-food-linked-to-lower-risk-of-death/
# "Ooh, this is exciting. So what does a 10% lower risk of death mean,
# to me, in the real world?"