Skip to content

Instantly share code, notes, and snippets.

View plumhead's full-sized avatar

Andy Calderbank plumhead

View GitHub Profile
@plumhead
plumhead / gist:c93bd759f986752228df
Created April 29, 2015 08:17
MKCoordinateRegion extension to determine region needed to fit a set of locations with zoom factor
extension MKCoordinateRegion {
static func region(forLocations waypoints: [CLLocation], zoomPercent: Double = 0.2) -> MKCoordinateRegion {
var r = MKMapRectNull
for wp in waypoints {
var point = MKMapPointForCoordinate(wp.coordinate)
r = MKMapRectUnion(r, MKMapRectMake(point.x, point.y, 0, 0))
}
let zoomed = MKMapRectMake(r.origin.x-r.size.width*zoomPercent, r.origin.y-r.size.height*zoomPercent, r.size.width*(1+zoomPercent*2), r.size.height*(1+zoomPercent*2))
@plumhead
plumhead / gist:832ee5226f26f76e8d57
Created April 29, 2015 15:01
Pairwise in Swift
func pairwise<T>(d: [T]) -> [(T,T)] {
switch d.count {
case 0: return []
case 1: return []
case let n:
let r = [(d[0],d[1])]
return r + pairwise(Array(d[1..<n]))
}
}
@plumhead
plumhead / StringSize.swift
Created September 15, 2015 13:34
String extension to find the layout size of a String with specified attributes.
extension String {
func size(withAttributes attrs: [String:AnyObject], constrainedTo box: NSSize) -> NSRect {
let storage = NSTextStorage(string: self)
let container = NSTextContainer(containerSize: NSSize(width: box.width, height: box.height))
let layout = NSLayoutManager()
layout.addTextContainer(container)
storage.addLayoutManager(layout)
storage.addAttributes(attrs, range: NSMakeRange(0, storage.length))
container.lineFragmentPadding = 0.0
let _ = layout.glyphRangeForTextContainer(container)
@plumhead
plumhead / SwiftExpr.swift
Created September 24, 2015 15:22
Playing with Swift Pattern Matching for Mathematical Expressions (run in playground)
import Cocoa
//: # An exercise in specifying and simplifying Maths functions using Swift
/*: This is cut-down version of some code I've been working on to parse, simplify and display mathematical expressions. The source below shows some of the power of pattern matching and (recursive) enumerated types within Swift in defining and evaluating the expression domain. Note, it doesn't cover all cases but is intended to give a flavour of what can be achieved.
No optimisations applied
*/
//: # Supporting functions
//: ### Function Pipeline
@plumhead
plumhead / NSTextViewExtensions.swift
Created November 13, 2015 16:38
Useful NSTextView extensions
extension NSTextView {
func rectForRange(range: NSRange) -> NSRect? {
guard let layout = self.layoutManager, container = self.textContainer else {return nil}
let rng = layout.glyphRangeForCharacterRange(range, actualCharacterRange: nil)
let rct = layout.boundingRectForGlyphRange(rng, inTextContainer: container)
return NSOffsetRect(rct, self.textContainerOrigin.x, self.textContainerOrigin.y)
}
func rectForSelectedRange() -> NSRect? {
return rectForRange(self.selectedRange())