Skip to content

Instantly share code, notes, and snippets.

View JanGorman's full-sized avatar
:shipit:

Jan Gorman JanGorman

:shipit:
View GitHub Profile
//: Playground - noun: a place where people can play
import UIKit
struct PriceTextProvider {
let basePrice: Double
let reducedPrice: Double
let vat: Double
typealias Age = Int
typealias Grow = Age -> Age
let getOlder: Grow = {
age in
age.successor()
}
getOlder(33)
@JanGorman
JanGorman / reusable-guard.swift
Created November 24, 2015 10:22
Swift tuple unwrapping for reusable guard statements
func foo(url: NSURL) {
guard let (components, path) = urlGuard(url) as? (NSURLComponents, String) else {
return
}
print("Components \(components) and path \(path)")
}
func urlGuard(url: NSURL) -> (NSURLComponents?, String?) {
guard let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false), path = components.path else {
return (nil, nil)
let numbers = AnySequence { () -> AnyGenerator<Int> in
var i = 1
return anyGenerator {
return i++
}
}.lazy
let fizzes = numbers.map{ $0 % 3 == 0 ? "Fizz" : "" }
let buzzes = numbers.map{ $0 % 5 == 0 ? "Buzz" : "" }
@JanGorman
JanGorman / iteration.swift
Created January 16, 2016 16:34
Neat iteration in Swift
for i in 1...10 where i % 2 == 0 {
print("\(i) is even")
}
for word in ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur",
"adipiscing", "elit"] where word.characters.count > 5 {
print(word, "is a long word")
}
for i in 1...50 where i > 20 && i < 30 && (i % 2 == 0) {
@JanGorman
JanGorman / doubleToRawLongBits.swift
Created April 5, 2016 09:18
doubleToRawLongBits in Swift
func doubleToRawLongBits(num: Double) -> Int64 {
var num = num
var bits: Int64 = 0
memcpy(&bits, &num, sizeofValue(bits))
return bits
}
extension Collection where Index: Strideable {
public func binarySearch(_ value: Iterator.Element,
isOrderedBefore: (Iterator.Element, Iterator.Element) -> Bool) -> Index? {
guard !isEmpty else { return nil }
var left = startIndex
var right = endIndex.advanced(by: -1)
while left <= right {
let mid = left.advanced(by: left.distance(to: right) / 2) // How does this work in Swift 4?
func toInt24(value: Int) -> NSData {
var result = [UInt8]()
result.append(UInt8(value >> 16))
result.append(UInt8(value >> 8))
result.append(UInt8(value))
return NSData(bytes: result, length: result.count)
}
func int24FromData(data: NSData, inout range: NSRange) -> Int {
let offset = sizeof(UInt8)
struct Video {
let title: String
let description: String?
let category: String
let thumbnailUrl: URL?
let …
}
// If you want to follow along in a Swift Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true
struct User: Codable {
let id: Int
let name: String
let email: String
}