Skip to content

Instantly share code, notes, and snippets.

@propertyWrapper
struct CopyOnWrite<Object> {
var wrappedValue: Object {
get { storage.object }
set {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.copy()
}
storage.object = newValue
}
struct Matrix<Element> {
private var storage: [[Element]]
init(_ storage: [[Element]]) {
self.storage = storage
}
}
extension Matrix: Collection {
struct Index: Comparable {
final class Node<Value>: Sequence {
typealias NextNode = Node<Value>?
let value: Value
var next: NextNode
init(value: Value, nextNode: NextNode = nil) {
self.value = value
self.next = nextNode
}
import Foundation
final class Threadsafe<Value> {
init(_ value: Value) {
self._value = value
}
var value: Value {
return queue.sync { return _value }
}
@jakebromberg
jakebromberg / AlmostIncreasingSequence.swift
Last active January 9, 2019 17:53 — forked from jakehawken/AlmostIncreasingSequence.swift
For the "almostIncreasingSequence" problem on CodeFights:
extension Sequence where Element: Comparable {
func isAlmostIncreasingSequence() -> Bool {
var foundMisplacedElement = false
for (a, b) in zip(self, self.dropFirst()) where a >= b {
guard !foundMisplacedElement else { return false }
foundMisplacedElement = true
}
@jakebromberg
jakebromberg / ThreadSafe.h
Last active August 24, 2018 18:54
Inspired by Chris Lattner's concurrency manifesto, this defines a generic thread-safe object in Objective-C, similar to how Chris describes the behavior of actors.
@import Foundation;
@interface ThreadSafe<Value>: NSProxy
- (instancetype)initWithValue:(Value)value;
@property (nonatomic, strong, readonly) Value value;
@end
@jakebromberg
jakebromberg / DisableNaglesAlgorithm.m
Last active June 12, 2018 03:32
Disables Nagle's Algorithm on a TCP socket
// Nagle's algorithm is a means of improving the efficiency of TCP/IP networks by reducing the number of packets that need to
// be sent over the network.
// https://en.wikipedia.org/wiki/Nagle%27s_algorithm
#import <netinet/in.h>
#import <netinet/tcp.h>
@implementation NSStream (DisableNaglesAlgorithm)
- (void)disableNaglesAlgorithmWithError:(NSError **)error {
final class WeakBox<A: AnyObject> {
weak var unbox: A?
init(_ value: A) {
unbox = value
}
}
typealias Callback<T> = (T) -> ()
final class Observation<T> {
final class ExecuteOnce {
typealias Work = () -> ()
private var work: Work?
init(_ work: @escaping Work) {
self.work = work
}
func execute() {
work?()
@jakebromberg
jakebromberg / SingleThreadedOperationQueue.swift
Last active May 2, 2018 22:57
Operation and dispatch queues on their own don't guarantee any single thread of execution. Here's one way to fix that.
import Foundation
@objc public final class SingleThreadedOperationQueue: Thread {
public typealias Operation = () -> ()
public func addOperation(_ operation: @escaping Operation) {
enqueueLock.lock()
defer {
enqueueLock.unlock()
}