Skip to content

Instantly share code, notes, and snippets.

@dfrib
dfrib / FibonacciSequence.swift
Last active October 23, 2016 20:03
Fibonacci numbers generation for Swift 3.0 & 3.1, using sequence(state:, next:) function
// --------------------------------------------------------------- //
// Swift 3.0:
func fibs(through: Int, includingZero useZero: Bool = false)
-> UnfoldSequence<Int, (Int, Int)> {
return sequence(state: useZero ? (1, 0) : (0, 1),
next: { (pair: inout (Int, Int)) -> Int? in
return pair.1 <= through ? {
defer { pair = (pair.1, pair.0 + pair.1) }
return pair.1 }() : nil
})
@dfrib
dfrib / DictionaryKeyPath.swift
Last active April 14, 2023 12:45
Swift: Reading and writing to (possible) nested dictionaries for a given key path, using a recursive approach
// For details, see
// http://stackoverflow.com/questions/40261857/remove-nested-key-from-dictionary
import Foundation
extension Dictionary {
subscript(keyPath keyPath: String) -> Any? {
get {
guard let keyPath = Dictionary.keyPathKeys(forKeyPath: keyPath)
else { return nil }
return getValue(forKeyPath: keyPath)