Created
January 28, 2020 18:16
-
-
Save Patrick-Kladek/4dce674dc67fe22652fa0d3256d9473b to your computer and use it in GitHub Desktop.
Wrapper to execute code only once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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