Skip to content

Instantly share code, notes, and snippets.

class ArrayImpl<T> {
var space: Int
var count: Int
var ptr: UnsafeMutablePointer<T>
init(count: Int = 0, ptr: UnsafeMutablePointer<T> = nil) {
self.count = count
self.space = count
@mikeash
mikeash / runtime-class.m
Created November 22, 2013 16:46
Creating a usable class purely at runtime using the Objective-C runtime APIs.
// clang -fobjc-arc -framework Foundation runtime-class.m
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Person : NSObject
- (id)initWithFirstName: (NSString *)firstName lastName: (NSString *)lastName age: (NSUInteger)age;
import Foundation
func machToNanoseconds(_ mach: UInt64) -> Double {
struct Static {
static var info: mach_timebase_info = {
var info = mach_timebase_info()
mach_timebase_info(&info)
return info
}()
}
extension Optional: Sequence {
public func makeIterator() -> Iterator {
return Iterator(optional: self)
}
public struct Iterator: IteratorProtocol {
var optional: Wrapped?
public mutating func next() -> Wrapped? {
defer { optional = nil }
let engine = AVAudioEngine()
func setup() {
let inputNode = engine.inputNode
let outputNode = engine.outputNode
NSLog("all: %@", AudioDevice.All().map{$0.name})
NSLog("inputs: %@", AudioDevice.All().filter{$0.isInput}.map{$0.name})
NSLog("outputs: %@", AudioDevice.All().filter{$0.isOutput}.map{$0.name})
@mikeash
mikeash / gist:5172803
Created March 15, 2013 20:18
Main thread watchdog
- (void)watchdog {
NSTimeInterval pingInterval = 1.0/60.0;
NSTimeInterval watchdogInterval = 1.0/30.0;
__block NSTimeInterval lastPing = 0;
NSProcessInfo *pi = [NSProcessInfo processInfo];
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, pingInterval * NSEC_PER_SEC, 0);
protocol Arithmeticable {
init(_ v: Int)
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
extension Int: Arithmeticable {}
extension Double: Arithmeticable {}
@import Foundation;
@import ObjectiveC;
static NSMutableSet *swizzledClasses;
static NSMutableDictionary *swizzledBlocks; // Class -> SEL (as string) -> block
static IMP forwardingIMP;
static dispatch_once_t once;
void Swizzle(Class c, SEL sel, void (^block)(NSInvocation *)) {
@mikeash
mikeash / blockforward.m
Created October 21, 2011 02:38
NSInvocation works for blocks too!
#import <dlfcn.h>
#import <Foundation/Foundation.h>
struct BlockDescriptor
{
unsigned long reserved;
unsigned long size;
void *rest[1];
class ObserverSetEntry<Parameters> {
weak var object: AnyObject?
let f: AnyObject -> Parameters -> Void
init(object: AnyObject, f: AnyObject -> Parameters -> Void) {
self.object = object
self.f = f
}
}