Skip to content

Instantly share code, notes, and snippets.

public enum NilOrdering {
case first, last
}
public enum SortOrdering {
case ascending, descending
}
public extension Sequence {
func sorted(on accessor: (Element) -> some Comparable, ordering: SortOrdering = .ascending) -> [Element] {
@khanlou
khanlou / Enum+CaseCountable.swift
Created November 15, 2016 18:19
count and allValues on Int-based enums
protocol CaseCountable { }
extension CaseCountable where Self : RawRepresentable, Self.RawValue == Int {
static var count: Int {
var count = 0
while let _ = Self(rawValue: count) { count+=1 }
return count
}
//stolen from @publicextension
extension Sequence {
func groupBy<T>(groupBy: (Iterator.Element) -> T) -> [T: [Iterator.Element]] {
var result: [T: [Iterator.Element]] = [:]
self.forEach { element in
let groupKey = groupBy(element)
result[groupKey] = (result[groupKey] ?? []) + [element]
}
extension SignedInteger {
func times(_ each: () -> ()) {
var count: Self = 0
while (count < self) { each(); count = count + 1 }
}
}
extension SignedInteger {
import Foundation
import Security
private let DataKey = "MyDataKey"
/**
* The KeychainResult class wraps an OSStatus that is returned from a keychain action. It vends KeychainErrors.
*/
struct KeychainResult {
let keychainError: OSStatus
@khanlou
khanlou / 1.swift
Created December 7, 2016 19:23
HeaderFormatter, through the refactorings
struct HeaderFormatter {
var text: String
var attributedString: NSAttributedString? {
guard let font = UIFont.champion(ofSize: 32) else { return nil }
let attributes: [NSString : AnyObject] = [NSFontAttributeName as NSString: font, NSForegroundColorAttributeName as NSString: UIColor.black, NSKernAttributeName as NSString : 1.5 as AnyObject]
return NSAttributedString(string: text, attributes: attributes as [String : Any]?)
}
@khanlou
khanlou / Quicksort.swift
Created December 9, 2016 02:43
Quicksort - the only use for partition(by:) I could find
import Foundation
extension Array where Element: Comparable {
mutating func quickSort() {
self[self.indices].quickSort()
}
}
extension ArraySlice where Element: Comparable {
mutating func quickSort() {
@khanlou
khanlou / NSArrays.swift
Created December 12, 2016 17:02
Converting an Array into an NSArray
import Foundation
let a = ["Asdf", "asdf"]
let nsArray1: NSMutableArray = a.reduce(NSMutableArray(), { array, task in array.add(task); return array })
nsArray1
let nsArray2 = NSArray(objects: a)
let nsArray3 = NSArray(array: a)
let nsArray4 = a as NSArray
extension BinaryFloatingPoint {
func rounded(to radix: Self) -> Self {
return (self/radix).rounded(.toNearestOrAwayFromZero)*radix
}
}
(55.325).rounded(to: 1/10) // => 55.3
import Foundation
final class Atomic<T> {
private let queue = DispatchQueue(label: "com.atomic.queue", attributes: [.concurrent])
private var value: T {
get {
return queue.sync {
return self.value