Skip to content

Instantly share code, notes, and snippets.

@vialyx
Last active October 17, 2018 18:22
Show Gist options
  • Save vialyx/9939a8d83e6bc4db4fc793163e414c3b to your computer and use it in GitHub Desktop.
Save vialyx/9939a8d83e6bc4db4fc793163e414c3b to your computer and use it in GitHub Desktop.
func swapTwo(_ a: inout Int, _ b: inout Int) {
(a, b) = (b, a)
}
var x = 4
var y = 7
swapTwo(&x, &y)
// What about two string, double, etc. ???
print("x: \(x)")
print("y: \(y)")
/*
x: 7
y: 4
*/
// Generic solution
func swapTwoGenerics<T>(_ a: inout T, _ b: inout T) {
(a, b) = (b, a)
}
swapTwoGenerics(&x, &y)
print("x: \(x)")
print("y: \(y)")
/*
x: 4
y: 7
*/
var first = "1"
var second = "2"
swapTwoGenerics(&first, &second)
print("first: \(first)")
print("second: \(second)")
/*
first: 2
second: 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment