Skip to content

Instantly share code, notes, and snippets.

func doThing(defaultable value: Int = 4, _ required: Void -> Int) -> Int {
return value + required()
}
doThing(defaultable: 4, { 6 }) // works
doThing { 6 } // works
doThing({ 6 }) // doesn't compile: Missing argument for parameter #2 in call
@khanlou
khanlou / MD5StringTest.swift
Last active April 12, 2019 09:18
MD5 and SHA1 on String in Swift 3
import XCTest
@testable import <#project#>
class StringMD5Test: XCTestCase {
func testMD5() {
let string = "soroush khanlou"
XCTAssertEqual(string.md5, "954d741d14b14002d1ba88f600eee635")
@khanlou
khanlou / Fonts.swift
Created October 6, 2016 21:10
Print all fonts in Swift 3
UIFont.familyNames.forEach({ familyName in
let fontNames = UIFont.fontNames(forFamilyName: familyName)
print(familyName, fontNames)
})
struct LinkedList<T> {
var head: Node<T>
init(head: Node<T>) {
self.head = head
}
}
indirect enum Node<T> {
@khanlou
khanlou / Sequence+Arithmetic.swift
Last active March 20, 2019 06:49
Sum on Sequence and Average on Array in Swift 4
extension Sequence where Self.Iterator.Element: Numeric {
var sum: Self.Iterator.Element {
return self.reduce(0, +)
}
}
extension Collection where Element: BinaryFloatingPoint {
var average: Element {
return self.reduce(0, +) / Element((0 as IndexDistance).distance(to: self.count))
}
@khanlou
khanlou / StateMachine.swift
Created October 21, 2016 00:14
A state machine where invalid transitions can't compile
protocol State {}
struct Transition<From: State, To: State> {
let transition: () -> To
}
struct Machine<CurrentState: State> {
var state: CurrentState
@khanlou
khanlou / Array+EachCons.swift
Last active July 7, 2020 17:48
each_cons from Ruby in Swift as a function on Sequence
extension Collection {
func eachConsecutive(_ size: Int) -> Array<SubSequence> {
let droppedIndices = indices.dropFirst(size - 1)
return zip(indices, droppedIndices)
.map { return self[$0...$1] }
}
}
@khanlou
khanlou / Times.swift
Created November 6, 2016 20:52
Ruby's n.times in Swift
extension SignedInteger {
func times() -> AnySequence<()> {
return AnySequence<()>({ () -> AnyIterator<()> in
var count: Self = 0
return AnyIterator<()>({
if count == self {
return nil
}
import Foundation
final class SafeSyncQueue {
struct QueueIdentity {
let label: String
}
let queue: DispatchQueue
import Foundation
extension Data {
var hexString1: String {
return self.map({ return String(format: "%02hhx", $0) }).joined()
}
var hexString2: String {
return self.reduce("", { return $0 + String(format: "%02hhx", $1) })