🇨🇦EN • 🇬🇧EN • 🇺🇸EN • 🇩🇪DE • 🇫🇷FR
APIs: macOS • Linux • iOS • watchOS • tvOS
⚠ This project is obsolete. It has been superseded by SDGCornerstone. ⚠
SDGCaching automates caching for results of complex or time‐consuming functions.
- Automated caching for results of complex or time‐consuming functions via
cached(in::)
.
(For a list of related projecs, see here.)
SDGCaching is intended for use with the Swift Package Manager.
Simply add SDGCaching as a dependency in Package.swift
:
let package = Package(
...
dependencies: [
...
.Package(url: "https://github.com/SDGGiesbrecht/SDGCaching", versions: "2.1.0" ..< "3.0.0"),
...
]
)
SDGCaching can then be imported in source files:
import SDGCaching
import SDGCaching
// This example uses SDGCaching to cache the computed properties of a structure.
private struct Number {
// MARK: - Initialization
init(value: Int) {
self.value = value
}
// MARK: - Stored Property
var value: Int {
willSet {
// Empty the cache whenever the value property changes.
cache = Cache()
}
}
// MARK: - Cache
private class Cache {
var square: Int?
var powers: [Int: Int] = [:]
}
private var cache = Cache()
// MARK: - Computed Properties
// These will only be executed once as long as the value property stays the same.
// When the value property changes, they will be re‐executed the next time they are needed.
var square: Int {
return cached(in: &cache.square) {
var result = 0
for _ in 1 ... value {
result += value
}
return result
}
}
func toPower(of exponent: Int) -> Int {
// This makes use of a dictionary to separate the cache for each exponent.
return cached(in: &cache.powers[exponent]) {
var result = 0
for _ in 1 ... exponent {
for _ in 1 ... value {
result += value
}
}
return result
}
}
}
The SDGCaching project is maintained by Jeremy David Giesbrecht.
If SDGCaching saves you money, consider giving some of it as a donation.
If SDGCaching saves you time, consider devoting some of it to contributing back to the project.
Ἄξιος γὰρ ὁ ἐργάτης τοῦ μισθοῦ αὐτοῦ ἐστι.
For the worker is worthy of his wages.
―ישוע/Yeshuʼa