Swapping in Swift

Varun
2 min readMay 7, 2020

--

Numerous ways to swap two variables

Credits: Rawpixel.com

You can read the full story along with many more on The Swift Nerd blog:

Prologue

When used to write code(before Swift/ Python), swapping two variables felt like to cumbersome to write. With the evolution of modern programming languages like Python, Kotlin, Swift the programming constructs are refined.

The primitive way

You declare a temporary variable, copy the value of the first variable in a temporary variable, assign the second variable to the first and finally copy temporary variable to the first one.

The hacky way

The normal swap needed to take a temporary variable which was a waste, so there should be a way without using extra space.

Python Way

Python introduced a simple swap method using lists to assign references. So if we create a list of two elements using shorthand notation and assign a list of elements in reversed order, then references of elements get interchanged.

Swifty Way

Swift introduced tuples, which enables to pair elements together. If we assign tuple in a reversed order, then the elements get reversed too.

Swift: Using generics in a function

In Swift, variables are passed as a value to function in arguments. So, function parameters become immutable. If you want to change the references, then you would have to declare them as an ‘inout’ parameter.

Swift packs powerful features that let us perform an operation in a simple and elegant way. This is one such example showing the use of tuples.

Thank you for reading! If you liked this article, please share it so other people can read it too.

You can find me on LinkedIn | Github | StackOverflow

--

--

No responses yet