Skip to content

Generic memoization utilities for Swift functions, supporting multiple parameters functions using parameter packs.

License

Notifications You must be signed in to change notification settings

Jaesung-Jung/Memoization

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Memoization

A lightweight and generic memoization utility for Swift. Supports multiple parameter functions using parameter packs.

Requirements

Swift 5.9+

Installation

Add this package to your Package.swift:

let package = Package(
  name: "YourProject",
  dependencies: [
    .package(url: "https://github.com/Jaesung-Jung/Memoization.git", .upToNextMajor(from: "1.0"))
  ],
  targets: [
    .target(
      name: "YourProject",
      dependencies: [
        .product(name: "Memoization", package: "Memoization")
      ]
    )
  ]
)

Usage

Parameterless function

let memoized = memoize {
    print("Computing…")
    return 42
}

print(memoized()) // First call: prints "Computing…"
print(memoized()) // Subsequent calls: returns cached value, no print

Function with parameters

let sum: (Int, Int) -> Int = memoize { a, b in
    print("Computing sum: \(a), \(b)")
    return a + b
}

print(sum(1, 2)) // First call with (1, 2): prints
print(sum(1, 2)) // Cache
print(sum(2, 3)) // First call with (2, 3): prints

Fibonacci example

func fibonacci(_ n: Int) -> Int {
  guard n > 1 else {
    return n
  }
  return fibonacci(n - 1) + fibonacci(n - 2)
}

let fibo = memoize(fibonacci)
let operatedValue = fibo(10)
let cacheValue = fibo(10)

print(operatedValue) // 55
print(cacheValue)    // 55

License

MIT license. See LICENSE for details.

About

Generic memoization utilities for Swift functions, supporting multiple parameters functions using parameter packs.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages