Skip to content

tornikegomareli/MemoizeMacro

Repository files navigation

MemoizeScreenshot

Swift Memoize Macro

A Swift macro for easy function memoization.

Overview

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.

Features

  • Easy to use: Just add @Memoize before 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 memoized prefix

Installation

Add this package to your project using Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/tornikegomareli/MemoizeMacro", from: "0.0.1")
]

Usage

  1. Import the package in your Swift file:
import Memoize
  1. Apply the @Memoize macro 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
    }
}
  1. 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 immediately

How It Works

The @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.

Requirements

  • Swift 5.9+
  • Xcode 15+

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Swift Memoize Macro: Effortless function memoization in Swift 👾

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages