store/[org.clojure/clojure "1.8.0"] clj::clojure.core/swap!

Community Documentation

Edit

Arities

[atom f]
[atom f x]
[atom f x y]
[atom f x y & args]

Docs

Atomically swaps the value of atom to be:

(apply f current-value-of-atom args)

Returns the value that was swapped in.

Notes

f may be called multiple times due to CAS transaction retry, and thus should be free of side effects.

See Also

Source

(defn swap!
  "Atomically swaps the value of atom to be:
  (apply f current-value-of-atom args). Note that f may be called
  multiple times, and thus should be free of side effects.  Returns
  the value that was swapped in."
  {:added "1.0"
   :static true}
  ([^clojure.lang.IAtom atom f] (.swap atom f))
  ([^clojure.lang.IAtom atom f x] (.swap atom f x))
  ([^clojure.lang.IAtom atom f x y] (.swap atom f x y))
  ([^clojure.lang.IAtom atom f x y & args] (.swap atom f x y args)))

Example 1

Edit
(def players (atom ()))
;; => #'user/players

(swap! players conj :player1)
;; => (:player1)

(swap! players conj :player2)
;; => (:player2 :player1)

(deref players)
;; => (:player2 :player1)

Example 2

Edit
(def counter (atom 0))
;; => #'user/counter

(swap! counter inc)
;; => 1

(swap! counter inc)
;; => 2

Uses on crossclj