Last active
October 17, 2018 18:22
-
-
Save vialyx/9939a8d83e6bc4db4fc793163e414c3b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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