Skip to content

Instantly share code, notes, and snippets.

View k0nserv's full-sized avatar

Hugo Tunius k0nserv

View GitHub Profile
@k0nserv
k0nserv / lazy-init.m
Last active August 29, 2015 13:56
Lazy init. Initialize the value of a variable only when it's first needed
@interface MyClass()
// Lazy inits are perfect for readonly values
// Note that strong can be used instead of copy here because
// we control the creation of the array and don't have to worry about
// being passed a mutable version
@property(nonatomic, readonly, strong) NSArray *values;
@end
@implementation MyClass
@k0nserv
k0nserv / person.h
Last active August 29, 2015 13:56
Setter with side effects
#import <Foundation/Foundation.h>
@interface Person
@property(nonatomic, copy) NSString *firstName;
@property(nonatomic, copy) NSString *lastName;
@property(nonatomic, readonly, strong) NSString *fullName
@end
def hours(open, close)
(0..6).to_a.map do |x|
{
start: x * 24 + open,
end: x * 24 + close
}
end
end
# Could be binary search
@k0nserv
k0nserv / async.swift
Created June 5, 2014 15:50
Conccurency in swift?
println("Before async")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
, {
println("async")
})
println("After async")
func _if(condition: BooleanType, action: () -> ()) {
if condition {
action()
}
}
_if(1 < 2) {
println("1 is less than 2")
}
@k0nserv
k0nserv / if-without-if.swift
Last active August 29, 2015 14:03
Reimplementing the swift if statement without using the if keyword
func _if_without_if(condition: BooleanType, action: () -> ()) {
// We fake the false case by using an empty closure, e.g a NOP
let actions = [{}, action]
// boolValue returns a Bool and we can abuse the fact that
// hashValue of true is 1 and then hashValue of false is 0 to
// get the correct closure to run
actions[condition.boolValue.hashValue]()
}
func _while(condition: @autoclosure () -> BooleanType, action: () -> ()) {
while condition() {
action()
}
}
var i = 0
_while(i < 10) {
println("\(i)")
i += 1
(function () {
"use strict";
// Code..
}());
func _while_without_while(condition: @autoclosure () -> BooleanType,
action: () -> ()) {
var loop: () -> () = { $0 }
loop = {
// The condition is called each time to
// see if the loop should continue
if condition() {
// Then the acutal action is called
action()
func unless(condition: BooleanType, action: () -> ()) {
if condition.boolValue == false {
action()
}
}
var opt: Int? = 10
unless(opt == nil) {
println("opt was non nil")
}