Skip to content

Instantly share code, notes, and snippets.

@seanwoodward
seanwoodward / Collection+random(pick:).swift
Last active June 7, 2019 03:19
Pick a number of random elements from an array. Better way?
extension Collection {
func random(pick: Int) -> [Element] {
return self.indices.shuffled().prefix(pick).map { self[$0] }
}
}
@seanwoodward
seanwoodward / Array+chunk.swift
Created June 6, 2019 13:51
Chunk an array into arrays of some size (or smaller)
extension Array {
/// Chunk an array in to an array of arrays of the provided size (or smaller)
/// - Parameters:
/// - size: the size of the chunk
/// - Returns: An array of arrays of `Element`
func chunked(into size: Int) -> [[Element]] {
return Swift.stride(from: 0, to: self.count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, self.count)])
}
}
@seanwoodward
seanwoodward / Adler32.swift
Created March 9, 2018 02:49
Adler32 using libz
import Foundation
import zlib
extension Array where Element == UInt8 {
func adler32() -> UInt32 {
let a1 = zlib.adler32(0, nil, 0)
let size = self.count
let result = self.withUnsafeBytes { (p1: UnsafeRawBufferPointer) -> UInt32 in
@seanwoodward
seanwoodward / PersistentContainer.swift
Created February 14, 2017 14:15 — forked from zwaldowski/PersistentContainer.swift
NSPersistentContainer backport to iOS 7 with Swift 3
import CoreData
@objc(_PersistentStoreDescription) private protocol AnyPersistentStoreDescription: NSObjectProtocol, NSCopying {
var type: String { get set }
var configuration: String? { get set }
@objc(URL) var url: URL? { get set }
var options: [String : NSObject] { get }
func setOption(_ option: NSObject?, forKey key: String)
@seanwoodward
seanwoodward / NSFetchRequestTypedResults.swift
Last active August 29, 2015 14:11
Typed results when executing NSFetchRequest
func executeFetchRequestT<T:AnyObject>(request:NSFetchRequest, managedObjectContext:NSManagedObjectContext, error: NSErrorPointer = nil) -> [T]? {
var localError: NSError? = nil
if let results:[AnyObject] = managedObjectContext.executeFetchRequest(request, error: &localError) {
if results.count > 0 {
if results[0] is T {
let asT:[T] = results as [T]
return .Some(asT)
}
@seanwoodward
seanwoodward / ViewController-snippet.m
Last active August 29, 2015 13:57
Auto-incrementing a value with UIButton and NSTimer or just use UIStepper
@interface ViewController
@property (nonatomic, weak) IBOutlet UILabel *numberLabel;
@property (nonatomic, strong) NSTimer *numberTimer;
@property (nonatomic, assign) double value;
@property (nonatomic, assign) BOOL cancelTimer;
@property (nonatomic, assign) NSTimeInterval timeInterval;
- (void)updateNumberLabel;
- (void)stopTimer;