Skip to content

Instantly share code, notes, and snippets.

@rayfix
rayfix / pokemon.swift
Created March 6, 2016 13:31
Pokemon Type Erasure (take 2)
//: Second Type Erasure
import Foundation
protocol Pokemon {
typealias Power
func attack(power: Power)
}
private class _AnyPokemonBoxBase<Power>: Pokemon {
protocol Actionable {
func action()
}
enum Planets: Actionable {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
protocol PlanetsKind {}
@rayfix
rayfix / simplenetwork.swift
Created June 25, 2016 17:20
A simple network request using NSURLSession
import UIKit
import XCPlayground
var str = "Hello, playground"
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["foo": "bar"]
struct PokeCorrall {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
//: Playground - noun: a place where people can play
import UIKit
extension String {
var isBlank: Bool {
return trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
}
}
@rayfix
rayfix / Cards.swift
Created October 16, 2016 17:58
Playing card abstraction
//: Cards
import Foundation
enum CardColor {
case red, black
}
enum CardSuit: CustomStringConvertible {
case heart, diamond, club, spade
import Foundation
private enum RandomSource {
static private let file = fopen("/dev/urandom","r")!
static private let queue = DispatchQueue(label: "random")
static func get(count: Int) -> [Int8] {
let capacity = count + 1 // fgets adds null termination
var data = UnsafeMutablePointer<Int8>.allocate(capacity: capacity)
defer {
data.deallocate(capacity: capacity)
let str = "acxz"
func isFunny(_ s: AnySequence<UInt8>) -> Bool {
let n1: [Int] = zip(s.dropFirst(), s).map { Int($0)-Int($1) }
let n2: [Int] = zip(s.reversed().dropFirst(), s.reversed()).map { Int($1)-Int($0) }
return n1 == n2
}
isFunny(AnySequence(str.utf8))
let str = "Hello, Keita"
var index = str.characters.startIndex
while index < str.characters.endIndex {
print(str.characters[index])
str.characters.formIndex(after: &index)
}
@rayfix
rayfix / LinkedList.swift
Created April 2, 2017 04:32
An alternate (slightly memory hungry) solution to the middle problem
public enum LinkedList<T> {
case end
indirect case node(value: T, next: LinkedList)
public func cons(_ value: T) -> LinkedList {
return .node(value: value, next: self)
}
}