Skip to content

Instantly share code, notes, and snippets.

@Patrick-Kladek
Created January 28, 2020 18:16
Show Gist options
  • Save Patrick-Kladek/4dce674dc67fe22652fa0d3256d9473b to your computer and use it in GitHub Desktop.
Save Patrick-Kladek/4dce674dc67fe22652fa0d3256d9473b to your computer and use it in GitHub Desktop.
Wrapper to execute code only once
//
// Once.swift
//
// Created by Patrick Kladek on 28.01.20.
//
import Foundation
/// `doOnce` Block can be called multiple times but will only run one time.
class Once: NSObject {
private var didRun: Bool
// MARK: - Lifecycle
override init() {
self.didRun = false
}
// MARK: Once
func doOnce(block: () -> Void) {
guard self.didRun == false else { return }
block()
self.didRun = true
}
func reset() {
self.didRun = false
}
}
/// Exmaple usage
// Add this as property to your class
let setupScrollPosition = Once()
// Somewhere in a function
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setupScrollPosition.doOnce {
// Do setup that should only run one time
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment