---
title: "compareExchange(expected:desired:successOrdering:failureOrdering:)"
framework: synchronization
role: symbol
role_heading: Instance Method
path: "synchronization/atomic/compareexchange(expected:desired:successordering:failureordering:)-5obt4"
---

# compareExchange(expected:desired:successOrdering:failureOrdering:)

Perform an atomic compare and exchange operation on the current value, applying the specified success/failure memory orderings.

## Declaration

```swift
func compareExchange(expected: consuming Value, desired: consuming Value, successOrdering: AtomicUpdateOrdering, failureOrdering: AtomicLoadOrdering) -> (exchanged: Bool, original: Value)
```

## Parameters

- `expected`: The expected current value.
- `desired`: The desired new value.
- `successOrdering`: The memory ordering to apply if this operation performs the exchange.
- `failureOrdering`: The memory ordering to apply on this operation does not perform the exchange.

## Return Value

Return Value A tuple (exchanged, original), where exchanged is true if the exchange was successful, and original is the original value.

## Discussion

Discussion This operation performs the following algorithm as a single atomic transaction: atomic(self) { currentValue in   let original = currentValue   guard original == expected else { return (false, original) }   currentValue = desired   return (true, original) } The successOrdering argument specifies the memory ordering to use when the operation manages to update the current value, while failureOrdering will be used when the operation leaves the value intact. note: This method implements a “strong” compare and exchange operation that does not permit spurious failures.
