A Swift macro for easy function memoization.
This package provides a @Memoize macro that automatically generates a memoized version of any function it's applied to. Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
- Easy to use: Just add
@Memoizebefore your function declaration - Supports functions with any number of parameters
- Works with various return types
- Automatically generates a memoized version of the function with a
memoizedprefix
Add this package to your project using Swift Package Manager:
dependencies: [
.package(url: "https://github.com/tornikegomareli/MemoizeMacro", from: "0.0.1")
]- Import the package in your Swift file:
import Memoize- Apply the
@Memoizemacro to any function you want to memoize:
class Calculator {
@Memoize
func expensiveCalculation(a: Int, b: Int) -> Int {
// Simulate expensive operation
sleep(2)
return a + b
}
}- Use the memoized version of the function by prefixing the original function name with
memoized:
let calculator = Calculator()
let result1 = calculator.memoizedExpensiveCalculation(a: 5, b: 3) // Takes 2 seconds
let result2 = calculator.memoizedExpensiveCalculation(a: 5, b: 3) // Returns immediatelyThe @Memoize macro generates a private cache and a new function with the memoized prefix. This new function checks the cache for previously computed results before calling the original function.
- Swift 5.9+
- Xcode 15+
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
