swift-once-macro

1.0.0

A macro to execute something just once
davdroman/swift-once-macro

What's New

1.0.0

2025-03-28T22:21:41Z

#once

CI

A Swift macro that makes it dead simple to execute something just once.

Motivation

Sometimes you want to ensure a piece of code only runs once—no matter how many times it's called. That’s what #once is for.

Just wrap your code in a #once block, and Swift will take care of the rest:

#once {
	print("Doesn't matter how many times this is called, it'll only be printed once")
}

This is useful for:

  • One-time side effects (e.g. analytics, logging)
  • Lazy initialization in non-global contexts
  • Ensuring swizzling or other runtime setup runs exactly once
  • Basically anything you only want to trigger just once

No need for custom flags, static vars, or DispatchOnce-style wrappers. Just write your code where you want it to run once, and be done with it.

Thread-safe and works with async code.

Getting Started

Add the package via Swift Package Manager:

.package(url: "https://github.com/davdroman/swift-once-macro", from: "1.0.0"),
.product(name: "Once", package: "swift-once-macro"),

Then import and use:

import Once

#once {
	// executes once, ever
}

That's it.

Description

  • Swift Tools 6.0.0
View More Packages from this Author

Dependencies

Last updated: Wed May 28 2025 05:42:30 GMT-0900 (Hawaii-Aleutian Daylight Time)