Skip to content

Instantly share code, notes, and snippets.

View oisdk's full-sized avatar

Donnacha Oisín Kidney oisdk

View GitHub Profile
func myFunc(i: Int, @noescape f: Int -> Bool) -> Bool {
return f(i)
}
func myFunc(i: Int) -> Bool {
return myFunc(i) { n in n % 2 == 0 }
}
func myFunc(i: Int, @noescape f: Int -> Int = {$0}) -> Int {
return f(i)
}
@oisdk
oisdk / json.swift
Last active November 23, 2015 12:28
public enum JSON {
case JString(String), JFloat(Double), JInt(Int)
case JArray([JSON]), JObject([String:JSON])
case JBool(Bool), null
}
extension JSON:
IntegerLiteralConvertible,
FloatLiteralConvertible,
BooleanLiteralConvertible,
private func handleNotificationAction(id: String?, userInfo: [NSObject: AnyObject], responseInfo: [NSObject: AnyObject]?, completion: () -> Void) {
let taskId = userInfo["extra"]?["task_hash"] as? String
let projectId = userInfo["extra"]?["project_hash"] as? String
let comment = responseInfo?["UIUserNotificationActionResponseTypedTextKey"] as? String
switch (id ,taskId,comment ,projectId) {
case let ("comment"? ,task? ,comment?,_ )
where !comment.isEmpty: print(task)
case let ("invitation_accept"? ,_ ,_ ,project? ): print(project)
case let ("invitation_decline"?,_ ,_ ,project? ): print(project)
/// Conforming types should be able to perform standard Vector addition
protocol VectorAddable {
// The syntax is confusing here: the protocol requires that conforming types have
// a + function defined on them. However, since a.+(b) doesn't make much sense,
// we're defining it as a static function, with unnamed parameters. In practice,
// this works just the same as a method. The function + for vectors has the same
// scope as the types it's defined on.
static func +(_: Self, _: Self) -> Self
}
extension SequenceType {
func myForEach(@noescape f: Generator.Element -> ()) {
for x in self {
f(x)
}
}
}
extension SequenceType {
func scan<T>(var initial: T, @noescape combine: (T, Generator.Element) -> T) -> [T] {
return map { e in
initial = combine(initial, e)
return initial
}
}
}
public struct FlatMapOptGenerator<G: GeneratorType, Element>: GeneratorType {
private let f: G.Element -> Element?
private var g: G
public mutating func next() -> Element? {
while let x = g.next() {
if let y = f(x) {
return y
}
}
return nil
@oisdk
oisdk / free.swift
Last active December 10, 2015 14:41
func free<A,B>(f: A -> () -> B) -> A -> B {
return { f($0)() }
}
[[1, 2, 3], [4, 5, 6]].map(free(Array.reverse)) // [[3, 2, 1], [6, 5, 4]]
public enum Either<A,B> {
case Left(A), Right(B)
}
public struct Trie<Element: Hashable> {
private var children: [Element:Either<Trie<Element>,[Element]>]
private var endHere: Bool
}
extension Trie {