Instantly share code, notes, and snippets.

View eff.swift
func effIt<Target, Result>(_ keypath: KeyPath<Target, Result>) -> (Target) -> Result {
return { $0[keyPath: keypath] }
}
struct Foo {
var x: Int
var y: Int
}
View test.mm
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
auto global = ^{ NSLog(@"Hello, world!"); };
auto captures = ^{ NSLog(@"argc is %d", argc); };
NSLog(@"global: %@ - captures: %@", global, captures);
NSLog(@"(void *)global: %p - (void *)captures: %p", (void *)global, (void *)captures);
id globalCopy = [global copy];
id capturesCopy = [captures copy];
View unwrap.swift
func ??<T>(lhs: T?, rhs: @autoclosure () throws -> Never) rethrows -> T {
guard let value = lhs else { try rhs() }
return value
}
func ??<T>(lhs: T?, rhs: () throws -> Never) rethrows -> T {
guard let value = lhs else { try rhs() }
return value
}
View dladdr.c
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
Dl_info info;
int success = dladdr(main, &info);
if (success == 0) abort();
printf("main is at %p and the mach-o header that contains it is at %p\n", main, info.dli_fbase);
}
View crash.swift
class C {}
protocol P where Self: C {
var x: Int { get }
var y: Int { get }
}
extension P {
var x: Int { return 42 }
}
View function.cpp
#include <iostream>
#include <functional>
using namespace std;
void f(std::function<void(int)> call) {
call(1);
call(2);
call(3);
}
View omniswizzle.m
@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 *)) {
View optional-sequence.swift
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 }
View nil-ptr.swift
let ptr = {}
func -<T>(lhs: T?, rhs: () -> Void) -> T? {
return nil
}
var d: [String: String] = [:]
d["one"] = "won"
d["two"] = "too"
d["one"] = nil-ptr
d["two"] = nil-ptr
View HeterogeneousCoresTest.swift
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
}()
}