Skip to content

Instantly share code, notes, and snippets.

@dnedrow
Forked from rnapier/doOnce.swift
Created May 15, 2018 14:46
Show Gist options
  • Save dnedrow/a2fbd9ef350e9a16aedfa22e20522b8f to your computer and use it in GitHub Desktop.
Save dnedrow/a2fbd9ef350e9a16aedfa22e20522b8f to your computer and use it in GitHub Desktop.

Revisions

  1. @rnapier rnapier revised this gist Nov 5, 2016. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions doOnce.swift
    Original file line number Diff line number Diff line change
    @@ -21,3 +21,6 @@ doOnce() // does not print

    // So is this good Swift that readers should simply learn to understand, or is it over-clever Swift
    // that has a better answer that is both idempotent and threadsafe?

    // I know the docs suggest just "evaluating a var with _ =" but that seems horrible compared to having a clear
    // function-call syntax.
  2. @rnapier rnapier created this gist Nov 5, 2016.
    23 changes: 23 additions & 0 deletions doOnce.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    // Swift3 gets rid of dispatch_once and recommends replacing it with a lazy global.
    // That's very straightforward when dispach_once is used to initialize something, but
    // isn't an exact match when you want something to execute once, and then become a noop
    // in a thread-safe way.

    // The following approach seems completely "correct" and I guess actually a bit elegant,
    // if by "elegant" you mean "terse and not immediately obvious to the reader, which makes
    // you look very clever."

    var doOnce: () -> Void = {
    // The side effect that should only happen once
    print("Running once, I hope")

    // A dummy function that's evaluated every time we're accessed
    return {}
    }()

    doOnce() // Prints
    doOnce() // does not print
    doOnce() // does not print

    // So is this good Swift that readers should simply learn to understand, or is it over-clever Swift
    // that has a better answer that is both idempotent and threadsafe?