A declarative, thread safe, and reentrant way to define code that should only execute at most once over the lifetime of an object.

Overview

SwiftRunOnce

SwiftRunOnce allows a developer to mark a block of logic as "one-time" code – code that will execute at most once over the lifetime of another object, no matter how many times that block of logic gets invoked.

SwiftRunOnce was designed to satisfy five requirements:

  • Robust implementation: A block of code to declared to be one-time code must be just that. There may be no circumstance in which the block of code is allowed to execute a second time over the lifetime of the controlling object.
  • Declarative usage: One must be able to make a block of preexisting code into one-time code simply by decorating with the attribute.
  • Thread safety: Even in multithreaded environments, a block of code marked with the one-time attribute must execute at most once.
  • Reentrancy: A block of one-time code must be able to invoke another block of one-time code without deadlocking or invalidating the one-time constraint.
  • Minimalist implementation: Adding a block of one-time code requires no additional storage or maintenance of state within the calling code. All state management is hidden and protected.

Usage

SwiftRunOnce exposes a single function:

forLifetime(
    of object: AnyObject,
    _ closure: () -> Void,
    line: Int = #line,
    column: Int = #column,
    fileId: String = #fileID
)

In actual usage, one should always use the default arguments for line, column, and fileId (the behavior when arguments are passed into these parameters is undefined). An example usage might look something like:

func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: animated)

    // Only fire on initial view, not on back navigation
    RunOnce.forLifetime(of: self) {
        trackView()
    }
}

Since most usages of forLifetime(of::) will pass self as the object, SwiftRunOnce adds a convenience extension to NSObject that adds a little more syntactic sugar to this common case. Using that extension, the above code simply becomes:

func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: animated)

    // Only fire on initial view, not on back navigation
    runOnce {
        trackView()
    }
}

License

SwiftRunOnce is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

You might also like...
Framework for easily parsing your JSON data directly to Swift object.
Framework for easily parsing your JSON data directly to Swift object.

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes

Swift Xid - Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings

Swift Xid - Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings

OwO.swift Badges go here in one line for the master branch ONLY.

OwO.swift Badges go here in one line for the master branch ONLY. Badges can also go in the header line. Short description describing the application/l

Pure Declarative Programming in Swift, Among Other Things

Basis The Basis is an exploration of pure declarative programming and reasoning in Swift. It by no means contains idiomatic code, but is instead inten

Safe and fast access to SwiftUI PreviewDevice

SafePreviewDevice Motivation At WWDC 2019, Apple announced SwiftUI a new library for building UI in a simple and fast way. Xcode’s SwiftUI preview let

Type-Safe Associated Objects in Swift

Type-Safe Associated Objects in Swift TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, b

Swift package for accessing SF Symbols in a type safe manner.

Swift Package Information Code Coverage Swift package for accessing SF Symbols in a type safe manner. Features 💫 Contains all SF Symbols - 1.0, 2.0,

🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.
🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

MediaType is a library that can be used to create Media Types in a type-safe manner.

This is a general purpose Swift library for a concept of typed treatment for Media Types. We use this library on clients and servers to speak the same dialect and to enjoy all the comfort strong types provide over raw strings.

Owner
Thumbtack
Thumbtack
Challenge... counting game for kids... should be entertaining, educational and fun... o_O

MultiTainment Simple multiplication game for kids. Possible to choose how many questions they want to answer and how hard shoud it be. Simple funny in

Pavel Surový 0 Dec 4, 2021
Because Objective-C should have inherited more from Smalltalk

OpinionatedC Sometimes, Objective-C is just overly verbose. Life is too short to enumerateObjectsUsingBlock and who has the time to create sub-arrays

Leo Schweizer 52 Apr 7, 2022
OTAtomics - Multi-platform Swift thread-safe atomics library

OTAtomics Multi-platform Swift thread-safe atomics library. The library has full

Steffan Andrews 2 Jul 8, 2022
A result builder that allows to define shape building closures

ShapeBuilder A result builder implementation that allows to define shape building closures and variables. Problem In SwiftUI, you can end up in a situ

Daniel Peter 47 Dec 2, 2022
⏲ A tiny package to measure code execution time. Only 20 lines of code.

Measure ⏲ A tiny package to measure code execution time. Measure.start("create-user") let user = User() Measure.finish("create-user") Console // ⏲ Mea

Mezhevikin Alexey 3 Oct 1, 2022
Simple utility for only executing code every so often.

Rate Limit Simple utility for only executing code every so often. This will only execute the block passed for a given name if the last time it was cal

Sam Soffes 921 Nov 20, 2022
Testable Combine Publishers - An easy, declarative way to unit test Combine Publishers in Swift

Testable Combine Publishers An easy, declarative way to unit test Combine Publishers in Swift About Combine Publishers are notoriously verbose to unit

Albert Bori 6 Sep 26, 2022
MetricTime is designed to be one universal timekeeping system that eliminates the hassle of calculating time since most of its convertions as simple as converting meters to centimeters

MetricTime MetricTime is designed to be one universal timekeeping system that eliminates the hassle of calculating time since most of its convertions

Adrian Edwards 4 Feb 10, 2022
A most fully customization calendar for Apple platforms 📅

KVKCalendar KVKCalendar is a most fully customization calendar. Library consists of five modules for displaying various types of calendar (day, week,

Kviatkovskii Sergei 353 Jan 5, 2023
This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to load remote images

iOS NOW ⭐ This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to loa

William Tristão de Paula 1 Dec 7, 2021